Page 150 - Beginning PHP 5.3
P. 150
Part II: Learning the Language
The four - element array that each() returns is itself a shining example of PHP ’ s flexibility with arrays,
because it contains elements with both numeric and string indices, as follows:
Element Index Element Value
0 The current element’s key
“key” The current element’s key
1 The current element’s value
“value” The current element’s value
In other words, you can use an index of either 0 or “ key ” to access the current element ’ s key, or an index
of 1 or “ value ” to access its value. For example:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$element = each( $myBook );
echo “Key: “ . $element[0] . “ < br/ > ”;
echo “Value: “ . $element[1] . “ < br/ > ”;
echo “Key: “ . $element[“key”] . “ < br/ > ”;
echo “Value: “ . $element[“value”] . “ < br/ > ”;
This code displays:
Key: title
Value: The Grapes of Wrath
Key: title
Value: The Grapes of Wrath
Here ’ s how to use each() to retrieve an array element with a value of false :
$myArray = array( false );
$element = each( $myArray );
$key = $element[“key”]; // $key now equals 0
$val = $element[“value”]; // $val now equals false
Because each() both returns the current array element and advances the array pointer, it ’ s easy to use it
in a while loop to move through all the elements of an array. The following example works through the
$myBook array, returning each element ’ s key and value as it goes. Figure 6-3 shows the result.
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Using each() with a while loop < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
112
9/21/09 9:00:12 AM
c06.indd 112
c06.indd 112 9/21/09 9:00:12 AM