Home > Backend Development > PHP Tutorial > Detailed explanation of PHP foreach traversing arrays

Detailed explanation of PHP foreach traversing arrays

PHPz
Release: 2023-03-07 09:38:02
Original
4289 people have browsed it

What is PHP foreach?

foreach is a convenient way to traverse 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.

PHP foreach has two syntaxes

There are two syntaxes, the second is relatively minor but is a useful extension of the first.

  • The first format iterates over 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).

    foreach (array_expression as $value)
      statement
    Copy after login
  • 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.

    foreach (array_expression as $key => $value)
      statement
    Copy after login

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 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)
?>
Copy after login

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;
}
?>
Copy after login

The above is the detailed content of Detailed explanation of PHP foreach traversing arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template