Page 89 - Open Soource Technologies 304.indd
P. 89
Open Source Technologies
Notes [name] => Barbara
[age] => 67
[age group] => Old
)
)
You can see that both the John and Barbara arrays inside the $people array were added an
additional value with their respective age group.
Traversing Arrays Using list() and each() Although foreach() is the nicer way of iterating
over an array, an additional way of traversing an array is by using a combination of the list()
construct and the each() function:
$players = array(“John”, “Barbara”, “Bill”, “Nancy”);
reset($players);
while (list($key, $val) = each($players)) {
print “#$key = $val\n”;
}
The output of this example is
#0 = John
#1 = Barbara
#2 = Bill
#3 = Nancy
reset() Iteration in PHP is done by using an internal array pointer that keeps record of the current
position of the traversal. Unlike with foreach(), when you want to use each() to iterate over an
array, you must reset() the array before you start to iterate over it. In general, it is best for you
to always use foreach() and not deal with this subtle nuisance of each() traversal.
each() The each() function returns the current key/value pair and advances the internal pointer
to the next element. When it reaches the end of of the array, it returns a booloean value of false.
The key/value pair is returned as an array with four elements: the elements 0 and “key”, which
have the value of the key, and elements 1 and “value”, which have the value of the value. The
reason for duplication is that, if you’re accessing these elements individually, you’ll probably
want to use the names such as:
$elem[“key”] and $elem[“value”]:
$ages = array(“John” => 28, “Barbara” => 67);
reset($ages);
$person = each($ages);
print $person[“key”];
84 LOVELY PROFESSIONAL UNIVERSITY