PHP 4 introduced the foreach construct, much like Perl and other languages. This is just a convenient way to iterate over an array. foreach can only be used with arrays, and an error will occur when trying to use it with other data types or an uninitialized variable. There are two syntaxes, the second being a less important but useful extension of the first.
Copy code The code is as follows:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $value and the pointer inside the array moves forward one step (so the next unit will be obtained in the next loop).
The second format does the same thing, except that the key name of the current cell will also be assigned to the variable $key in each loop.
Since PHP 5, it is also possible to traverse objects.
Note: When foreach starts executing, the pointer inside the array will automatically point to the first unit. This means there is no need to call reset() before the foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array, not the array itself. foreach has some side effects on array pointers. Do not rely on the value of an array pointer during or after a foreach loop unless it is reset.
Since PHP 5, it is easy to modify the elements of an array by preceding $value with &. This method assigns by reference rather than copying a value.
Copy code The code is as follows:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>
This method is only available when the array being traversed can be referenced (for example, it is a variable).
Copy code The code is as follows:
foreach (array(1, 2, 3, 4 ) as &$value) {
$value = $value * 2;
}
?>
http://www.bkjia.com/PHPjc/327824.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327824.htmlTechArticlePHP 4 introduces the foreach structure, which is very similar to Perl and other languages. This is just a convenient way to iterate over an array. foreach can only be used with arrays, when trying to use it with other data types or...