foreach
PHP 4 introduced a foreach construct, much
like Perl and some other languages. This simply gives an easy way to
iterate over arrays. foreach works only on arrays, and
will issue an error when you try to use it on a variable with a different
data type or an uninitialized variable. There are two syntaxes; the
second is a minor but useful extension of the first:
The first form loops over the array given by
array_expression. On each loop, the value of
the current element is assigned to $value and
the internal array pointer is advanced by one (so on the next
loop, you'll be looking at the next element).
The second form does the same thing, except that the current
element's key will be assigned to the variable
$key on each loop.
As of PHP 5, it is possible to
iterate objects too.
Note:
When foreach first starts executing, the
internal array pointer is automatically reset to the first element
of the array. This means that you do not need to call
reset() before a foreach
loop.
Note:
Unless the array is referenced,
foreach operates on a copy of
the specified array and not the array itself. foreach
has some side effects on the array pointer. Don't rely on the array
pointer during or after the foreach without resetting it.
As of PHP 5, you can easily modify array's elements by preceding
$value with &. This will assign
reference instead of copying
the value.
This is possible only if iterated array can be referenced (i.e. is
variable).
Warning
Reference of a $value and the last array element
remain even after the foreach loop. It is recommended
to destroy it by unset().
Note:
foreach does not support the ability to
suppress error messages using '@'.
You may have noticed that the following are functionally
identical:
The following are also functionally identical:
Some more examples to demonstrate usages: