foreach
is a special kind of looping statement that works only on arrays and objects.
foreach
can be used in two ways.
Use foreach to retrieve each element's value, as follows:
foreach ( $array as $value ) { // (do something with $value here) } // (rest of script here)
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)
Use foreach loop to get value
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
foreach ( $authors as $val ) {
echo $val . "\n";
}
?>
The code above generates the following result.
Use foreach to loop through associate array
<?php //from ww w . ja va2s . c o m
$myBook = array( "title" => "Learn PHP from java2s.com",
"author" => "java2s.com",
"pubYear" => 2000 );
foreach ( $myBook as $key => $value ) {
echo "$key \n";
echo "$value \n";
}
?>
The code above generates the following result.
When using foreach, the values inside the loop are copies of the values.
If you change the value, you're not affecting the value in the original array. The following example code illustrates this:
<?PHP/*www .j a va 2 s. c o m*/
$authors = array( "Java", "PHP", "CSS", "HTML" );
// Displays "Java PHP Javascript HTML";
foreach ( $authors as $val ) {
if ( $val == "CSS" ) $val = "Javascript";
echo $val . " ";
}
print_r ( $authors );
?>
The code above generates the following result.
Although $val was changed from "CSS" to "Javascript" within the loop, the original $authors array remains untouched.
To modify the array values, we need to get foreach() to return a reference to the value in the array, rather than a copy.
To work with references to the array elements, 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:
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
foreach ( $authors as & $val ) {
if ( $val == "CSS" ) $val = "Javascript";
echo $val . " ";
}
unset( $val );
print_r ( $authors );
?>
The code above generates the following result.
This time, the third element's value in the $authors array is changed from "CSS" to "Javascript" in the array itself.
The unset($val)
ensures that the $val
variable is deleted after the
loop has finished.
When the loop finishes, $val still holds a reference to the last element. Changing $val later in our code would alter the last element of the $authors array. By unsetting $val, we avoid potential bug.