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:
- $authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
- // Displays "Steinbeck Kafka Hardy Dickens";
- foreach ( $authors as $val ) {
- if ( $val == "Tolkien" ) $val = "Hardy";
- echo $val . " ";
- }
- echo "<br/>";
- // Displays "Array ( [0] => Steinbeck [1] => Kafka [2] => Tolkien [3] => Dickens )"
- 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:
- $authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
- // Displays "Steinbeck Kafka Hardy Dickens";
- foreach ( $authors as &$val ) {
- if ( $val == "Tolkien" ) $val = "Hardy";
- echo $val . " ";
- }
- unset( $val );
- echo "<br/>";
- // Displays "Array ( [0] => Steinbeck [1] => Kafka [2] => Hardy [3] => Dickens )"
- 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.