Using foreach to Loop Through PHP Arrays

How to use PHP's foreach construct to loop through PHP array elements.

Using foreach() to Loop Through PHP Arrays

Often you need to move through all the elements in a PHP array so that you can do something with each element's value. For example, you may want to display each value in an HTML table, or give each element a new value.

In Counting PHP Array Elements Using count(), I showed how you can use a for loop along with the count() function to loop through an array. However, there's a much easier way to loop through arrays: the foreach construct.

In this article you learn the basic syntax of foreach, and see how to use it to loop through both indexed and associative arrays.

Looping through element values

The simplest way to use foreach is when looping through the values in an indexed array. Here's the basic syntax:


foreach ( $array as $value ) {
  // Do stuff with $value
}

// This code runs after the loop finishes

For example, the following script loops through a list of movie directors in an indexed array, displaying each director's name as it goes:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

foreach ( $directors as $director ) {
  echo $director . "<br />";
}

The above script produces the following output:


Alfred Hitchcock
Stanley Kubrick
Martin Scorsese
Fritz Lang

Looping through keys and values

So far so good, but what about associative arrays? With these types of arrays, you often want to access each element's key as well as its value. Luckily, foreach gives you a way to do just that:


foreach ( $array as $key => $value ) {
  // Do stuff with $key and/or $value
}

// This code runs after the loop finishes

Here's an example that loops through an associative array of movie information, displaying each element's key and value inside an HTML definition list:


$movie = array( "title" => "Rear Window",
                "director" => "Alfred Hitchcock",
                "year" => 1954,
                "minutes" => 112 );

echo "<dl>";

foreach ( $movie as $key => $value ) {
  echo "<dt>$key:</dt>";
  echo "<dd>$value</dd>";
}

echo "</dl>";

This script displays the following:


title:
    Rear Window
director:
    Alfred Hitchcock
year:
    1954
minutes:
    112

Altering element values

So far you've just looked at reading element values, but what if you want to change values as you loop through? You might try something like this:


foreach ( $myArray as $value ) {
  $value = 123;
}

However, if you do this you'll find that your array values aren't changed. This is because foreach works on a copy of the array values, rather than the original array. So the original array remains untouched.

To change array values, you need to reference the values. You do this by placing an ampersand (&) before the value variable in the foreach construct:


foreach ( $myArray as &$value ) {
  $value = 123;
}

$value then becomes a reference to the element value in the original array, which means you can change the element by assigning a new value to $value.

A reference is a pointer to the original value, rather than a copy of the value. It's a bit like a shortcut in Windows, or an alias in Mac OS.

For example, the following script loops through each director in the $directors array, and uses PHP's explode() function and list construct to reverse the director's first and last names:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Change the name format for each element to "last, first"
foreach ( $directors as &$director ) {
  list( $firstName, $lastName ) = explode( " ", $director );
  $director = "$lastName, $firstName";
}

unset( $director );

// Output the final array
foreach ( $directors as $director ) {
  echo $director . "<br />";
}

This script outputs the following:


Hitchcock, Alfred
Kubrick, Stanley
Scorsese, Martin
Lang, Fritz

Notice that the script calls unset() to delete the $director variable after it's been used as a reference in the first loop. This is always a good idea if you think you might want to use the variable later in the script in a different context.

If you don't delete the reference then you run the risk of accidentally referencing the last element in the array ("Lang, Fritz") when you next use the $director variable, with often quite unexpected consequences!

In case you're wondering, you can only change array values in a foreach loop. You can't change array keys.

Summary

In this tutorial you've seen how to use PHP's foreach construct to move through the elements in an array. You've looked at:

  • How to loop through array elements
  • How to access each element's key and value within the loop
  • Using references to alter array values as you loop through the array

You can now easily create code that works on entire arrays, reading or changing array values as you go. Happy coding!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

2 responses (oldest first):

19-Aug-11 13:31
Matt,

Thanks for this very helpful article!

Strangely, the beginner PHP books did not mention how to use foreach to change the value of an array. You would think this is an obvious need.

Anyway, after spending quite a few head-scratching minutes wondering why my foreach was not working, I happily found your article. "Ferris Buehler, you're my hero."
23-Aug-11 22:43
No problem Bill - glad it helped!

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page