4.4. Iterating Through an Array
Problem
You want to cycle though an array and operate on all or some of the elements inside.
Solution
Use foreach
:
foreach ($array as $value) {
// Act on $value
}Or, to get an array’s keys and values:
foreach ($array as $key => $value) {
// Act II
}Another technique is to use
for
:
for ($key = 0, $size = count($array); $key < $size; $key++) {
// Act III
}Finally, you can use
each( ) in
combination with list( ) and
while:
reset($array) // reset internal pointer to beginning of array
while (list($key, $value) = each ($array)) {
// Final Act
}Discussion
A foreach loop is the shortest way to iterate
through an array:
// foreach with values
foreach ($items as $cost) {
...
}
// foreach with keys and values
foreach($items as $item => $cost) {
...
}With foreach, PHP iterates over a copy of the
array instead of the actual array. In contrast, when using
each( ) and for, PHP iterates
over the original array. So, if you modify the array inside the loop,
you may (or may not) get the behavior you expect.
If you want to modify the array, reference it directly:
reset($items);
while (list($item, $cost) = each($items)) {
if (! in_stock($item)) {
unset($items[$item]); // address the array directly
}
}The variables returned by each( )
aren’t aliases for the original values in the array:
they’re copies, so, if you modify them,
it’s not reflected in the array.
That’s why you need to modify
$items[$item] instead of $item.
When using each( ), PHP keeps track of where you ...