The use of the second way refers to the passage by reference, that is, if you change the value it contains in $value
will change at the memory 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 the content is automatically changed in the other, as they are linked to the same memory position.
Source
One should check if there are any performance issues, there is a topic on this
Foreach by reference or value?
Regarding the commenting, in this 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: http://sandbox.onlinephpfunctions.com/code/be707e3b92448c5ce26c56dda7e98edeb74054ec
& means you’re using the reference. Thus $value has a reference to a position of your array, changing $value the value is changed at the position of your array automatically.
– Don't Panic
Example at this link: https://answall.com/q/158546/57801
– Don't Panic
If in foreach without reference, I modify the value of $value, I won’t be changing the value within the array?
– Pedro Souza
No, you need to re-assign to the array, or the change is only in the variable as long as it exists in the cycle, when the cycle is completed the change is lost and in the new cycle the next position of the array is assigned.
– Don't Panic
PHP documentation: http://php.net/manual/en/language.references.whatdo.php
– Don't Panic
In the following case, I make changes without the reference and they are maintained, see: http://sandbox.onlinephpfunctions.com/code/ee080b3cf307eb359545e8d6594f32d6a208acf6
– Pedro Souza
It’s the same principle as the reference, you’re instantiating a class and putting it inside an array, but the classes work directly with reference. Thus, if you change any class attribute, all the places that have the class reference will be changed as well. An example is this one, created a class and assigned 2 variables, changing the value in one of them will change in the other.
– Don't Panic