Page 154 - Beginning PHP 5.3
P. 154
Part II: Learning the Language
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 unset ting (deleting) $val , you safeguard against this
potential bug.
References are a powerful tool, and they ’ re explained in more detail in the next chapter.
Working with Multidimensional Arrays
So far, all the arrays you ’ ve worked with in this chapter have contained simple values, such as strings
and integers. However, arrays can get a lot more powerful than this. As mentioned in “ The Anatomy of
an Array, ” earlier in this chapter, PHP arrays can store values of any type. This includes resources,
objects, and, more importantly, other arrays.
116
9/21/09 9:00:14 AM
c06.indd 116 9/21/09 9:00:14 AM
c06.indd 116