Home > Backend Development > PHP Tutorial > How Does PHP's Pass by Reference in `foreach` Loops Affect Array Element Modification?

How Does PHP's Pass by Reference in `foreach` Loops Affect Array Element Modification?

Barbara Streisand
Release: 2024-12-17 12:42:25
Original
770 people have browsed it

How Does PHP's Pass by Reference in `foreach` Loops Affect Array Element Modification?

PHP Pass by Reference in foreach

Understanding Pass by Reference

PHP has two variable types: normal variables and reference variables. Assigning a reference of a variable to another variable creates a reference variable. The variable becomes an alias for the referenced variable.

Pass by Reference in Foreach Loops

In a foreach loop, the syntax foreach ($a as &$v) passes a reference to each array element to the variable $v. This means that any changes made to $v inside the loop will also modify the original array element.

Explanation of the Code Snippet

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
  echo $v.PHP_EOL;
}
Copy after login

In this code:

  1. The array $a contains four elements: 'zero', 'one', 'two', and 'three'.
  2. The first foreach loop iterates through each element and passes a reference to each element to $v.
  3. No changes are made to $v within this loop, so the array elements remain unchanged.
  4. The second foreach loop iterates through each element again, but this time, a normal variable $v holds the value of each element.
  5. The output will be:
zero
one
two
two
Copy after login

Reason for the Output

After the first foreach loop, the element $a[3] becomes a reference variable since it is being referenced by $v. Therefore, when $v is assigned a new value in the subsequent iterations, $a[3] is also modified.

Since $a[3] is now a reference variable, changing its value in the second foreach loop affects all other iterations of the loop. Hence, the last iteration prints 'two' instead of 'three'.

The above is the detailed content of How Does PHP's Pass by Reference in `foreach` Loops Affect Array Element Modification?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template