Home > Backend Development > PHP Tutorial > Why does PHP's foreach with pass-by-reference (&) change array elements unexpectedly?

Why does PHP's foreach with pass-by-reference (&) change array elements unexpectedly?

DDD
Release: 2024-12-11 04:41:09
Original
431 people have browsed it

Why does PHP's foreach with pass-by-reference (&) change array elements unexpectedly?

PHP Pass by Reference in Foreach

In PHP, variables can be either normal variables or reference variables. When assigning a reference of a variable to another variable, the latter becomes a reference variable, essentially binding to the same memory location as the original. This behavior has implications when using the foreach loop with the pass-by-reference syntax (&).

Consider the following code:

$a = ['zero', 'one', 'two', 'three'];

foreach ($a as &$v) {

}

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

The output of this code is:

zero one two two
Copy after login

Why does this occur?

In the first foreach loop, each element of $a is assigned as a reference to the variable $v. This means that any modification to $v also modifies the corresponding element in $a.

Specifically, during the last iteration of the first loop, $v is assigned the value of $a[3] (i.e., 'three'). However, this assignment creates a reference relationship, so $a[3] becomes a reference variable (even though it is not assigned explicitly using &).

In the second foreach loop, the values of the elements in $a are printed. However, since $a[3] is now a reference variable, its value changes along with the value of $v. When $v is assigned the value 'two' during the third iteration, $a[3] also becomes 'two'.

As a result, in the last iteration, $v (which still points to $a[3]) has the value 'two', and 'two' is printed. This explains why 'two' is repeated in the last iteration, instead of printing 'three' as one might intuitively expect.

The above is the detailed content of Why does PHP's foreach with pass-by-reference (&) change array elements unexpectedly?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template