Using Foreach in PHP

4

The foreach constructor provides an easy way to iterate over arrays . In several scripts we can observe the following usage:

foreach ($array as $value) {
    $value = $value * 2;
}

However, in some cases the following use is possible:

foreach ($array as &$value) {
    $value = $value * 2;
}

What exactly would be the character & accompanied by the variable $value , and what its effect inside the command foreach ?

    
asked by anonymous 16.06.2017 / 16:41

1 answer

2

The use of the second way refers to passing by reference, that is, if you change the value contained in $value will change in the memory position relative to the position of the array being traversed.

To better understand:

What references do

References in PHP allow you to create two or more variables that refer to the same content. That is, when you do:

<?php
$a =& $b;
?>

so here $a and $b point to the same content. Changing any of the two variables automatically changes the content in the other, because they are linked to the same memory location.

Font

You should check for performance issues, there is a topic about it

Foreach by reference or by value?

Referring to the comment , in that case you are changing the value of a class and not a value in the array.

Changing the class attribute will change where all instances of it are.

Example: link

    
16.06.2017 / 19:15