foreach

The foreach construct simply gives an easy way to iterate over arrays. foreach works only on arrays (and objects), 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:

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

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.

<html>
<head>
<title>foreach</title>
</head>
<body>
<p>
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    echo $value;
}?>
</body>
</html>