php 6

6.4 Looping Through Arrays with foreach
As you just saw, it's easy to use each() in combination with while to loop through all the elements of an array. In fact, there's an even easier way: you can use PHP's foreach statement.

foreach is a special kind of looping statement that works only on arrays (and objects). You can use it in two ways. You can either retrieve just the value of each element, or you can retrieve the element's key and value.
Using foreach to Loop Through Values
The simplest way to use foreach is to retrieve each element's value, as follows:
 foreach ( $array as $value )
   // (do something with $value here)
 // (rest of script here)

As you might imagine, the foreach loop continues to iterate until it has retrieved all the values in the array, from the first element to the last. On each pass through the loop, the $value variable gets set to the value of the current element. You can then do whatever you need to do with the value within the loop's code block. Then, the loop repeats again, getting the next value in the array, and so on.

Here's an example:

  1. $authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
  2. foreach ( $authors as $val )
  3. {
  4. echo $val . "<br/>";
  5. }

This code displays:

Note that you can use any variable name you like to store the value. Essentially, any variable that you place after the as in the foreach statement gets assigned the current element's value.
Try it yourself: Using foreach to Loop Through Values
Using foreach to Loop Through Keys and Values
To use foreach to retrieve both keys and values, use the following syntax:
 foreach ( $array as $key => $value ) {
   // (do something with $key and/or $value here
 // (rest of script here)

This behaves exactly like the previous foreach construct; the only difference is that the element's key is also stored in the $key variable. (Again, you can use any variable names you like; they don't have to be $key and $value.)

Now you can rewrite the example that used each() with a while loop in the previous section ("Stepping Through an Array") to use a foreach loop instead:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2. "">
  3. <html xmlns="" xml:lang="en" lang="en">
  4. <head>
  5. <title>Using foreach</title>
  6. <link rel="stylesheet" type="text/css" href="common.css" />
  7. </head>
  8. <body>
  9. <h1>Using foreach</h1>
  10. <dl>
  11. <?php
  12. $myBook = array( "title" => "The Grapes of Wrath",
  13. "author" => "John Steinbeck",
  14. "pubYear" => 1939 );
  15. foreach ( $myBook as $key => $value ) {
  16. echo "<dt>$key</dt>";
  17. echo "<dd>$value</dd>";
  18. }
  19. ?>
  20. </dl>
  21. </body>
  22. </html>

This code produces the same list of keys and values as shown in Figure 6-3.
Altering Array Values with foreach
When using foreach, the values you work with inside the loop are copies of the values in the array itself. This means that if you change the value given to you by foreach, you're not affecting the corresponding value in the original array. The following example code illustrates this:

  1. $authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
  2. // Displays "Steinbeck Kafka Hardy Dickens";
  3. foreach ( $authors as $val ) {
  4. if ( $val == "Tolkien" ) $val = "Hardy";
  5. echo $val . " ";
  6. }
  7. echo "<br/>";
  8. // Displays "Array ( [0] => Steinbeck [1] => Kafka [2] => Tolkien [3] => Dickens )"
  9. print_r ( $authors );

Notice that, although $val was changed from "Tolkien" to "Hardy" within the loop, the original $authors array remains untouched, as evidenced by the output from print_r() on the final line.

However, if you do want to modify the array values themselves, you can get foreach() to return a reference to the value in the array, rather than a copy. This means that the variable within the loop points to the value in the original array element, allowing you to change the element's value simply by changing the variable's value.

To work with references to the array elements rather than copies of the values, simply add a & (ampersand) symbol before the variable name within the foreach statement:
 foreach ( $array as &$value ) {

Here's the previous example rewritten to use references:

  1. $authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
  2. // Displays "Steinbeck Kafka Hardy Dickens";
  3. foreach ( $authors as &$val ) {
  4. if ( $val == "Tolkien" ) $val = "Hardy";
  5. echo $val . " ";
  6. }
  7. unset( $val );
  8. echo "<br/>";
  9. // Displays "Array ( [0] => Steinbeck [1] => Kafka [2] => Hardy [3] => Dickens )"
  10. print_r ( $authors );

Notice how, this time, the third element's value in the $authors array is changed from "Tolkien" to "Hardy" in the array itself.

By the way, the unset( $val ) line ensures that the $val variable is deleted after the loop has finished. This is generally a good idea, because when the loop finishes, $val still holds a reference to the last element (that is, "Dickens"). If you were to change $val later in your code, you would inadvertently alter the last element of the $authors array. By unsetting (deleting) $val, you safeguard against this potential bug.

References are a powerful tool, and they're explained in more detail in the next chapter.


Do you want to join discussion? Click here to log in or create user.