Home  >  Article  >  Backend Development  >  Functions in PHP - Detailed explanation of the usage of foreach()

Functions in PHP - Detailed explanation of the usage of foreach()

高洛峰
高洛峰Original
2017-01-16 13:20:031452browse

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.

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

The first format traverses the given array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop).

The second format does the same thing, except that the key name of the current unit 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, you can easily modify the elements of an array by adding & before $value. This method assigns by reference rather than copying a value.

<?php
$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).

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

For more functions in PHP - detailed explanation of the usage of foreach(), please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn