Page 162 - Open Soource Technologies 304.indd
P. 162
Web Technologies-I
Notes 7.4 Traversing Arrays
The most common task with arrays is to do something with every elements, for instance, sending
mail to each element of an array of addresses, updating each file in an array of filenames, or
adding up each element of an array of prices. There are several ways to traverse arrays in PHP,
and the one you choose will depend on your data and the task you’re performing.
7.4.1 The for each Construct
The most common way to loop over elements of an array is to use the foreach construct:
$addresses = array (‘spam@cyberpromo.net’, ‘abuse@example.com’);
foreach ($addresses as $value) {echo “Processing $value\n”;
}
Processing spam@cyberpromo.net Processing abuse@example.com
PHP executes the body of the loop (the echo statement) once for each element of $addresses
in turn, with $value set to the current element. Elements are processed by their internal order.
An alternative form of foreach gives you access to the current key:
$person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘Riya’);
foreach ($person as $k => $v) {
echo “Pradip’s $k is $v\n”;
}
Pradip’s name is Pradip
Pradip’s age is 35
Pradip’s wife is Riya
In this case, the key for each element is placed in $k and the corresponding value is placed in $v.
The foreach construct does not operate on the array itself, but rather on a copy of it. You can
insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won’t
attempt to process the deleted or inserted elements.
7.4.2 The Iterator Functions
Every PHP array keeps track of the current element you’re working with; the pointer to the
current element is known as the iterator. PHP has functions to set, move, and reset this iterator.
The iterator functions are:
current( )
Returns the element currently pointed at by the iterator
reset( )
Moves the iterator to the first element in the array and returns it
next ( )
Moves the iterator to the next element in the array and returns it
prev( )
Moves the iterator to the previous element in the array and returns it
156 LOVELY PROFESSIONAL UNIVERSITY