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; }
In this code:
zero one two two
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!