The functions in PHP foreach of are explained in detail

  • 2020-06-19 09:55:48
  • OfStack

PHP 4 introduces the foreach structure, much like Perl and other languages. This is just a simple way to iterate over a set of Numbers. foreach can only be used with arrays, and an error occurs when you try to use it for another data type or an uninitialized variable. There are two grammars, the second being a minor but useful extension to the first.

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

The first format iterates over the given array_expression array. In each loop, the value of the current cell is assigned to $value and the pointer inside the array moves forward by one step (so the next cell will be returned in the next loop).

The second format does the same, except that the key name of the current cell is also assigned to the variable $key in each loop.
Starting with PHP 5, it is also possible to traverse objects.

Note: When foreach starts executing, the pointer inside the array automatically points to the first cell. This means that 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 with array Pointers. Do not rely on the value of the array pointer in or after the foreach loop unless it is reset.
Starting with PHP 5, this can easily be passed by adding before $value & To modify the elements of the array. This method assigns a value by reference instead of 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 if the traversed array can be referenced (for example, a variable).

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


Related articles: