Traversing Arrays in php

The most common task with arrays is to do something with every element—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

The foreach Construct

The most common way to loop over elements of an array is to use the foreach construct:

$addresses = array("[email protected]", "[email protected]");
foreach ($addresses as $value) {
 echo "Processing {$value}\n";
}
Processing [email protected]
Processing [email protected]

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

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' => "Fred", 'age' => 35, 'wife' => "Wilma");
foreach ($person as $key => $value) {
 echo "Fred's {$key} is {$value}\n";
}
Fred's name is Fred
Fred's age is 35
Fred's wife is Wilma

Leave a Comment