What is the difference between
foreach ($my_array as $my_value) {
}
And:
foreach ($my_array as &$my_value) {
}
Jonathan's answers describes it very well. Just for completeness, here are your two examples:
Just reading values:
$my_array = range(0,3);
foreach ($my_array as $my_value) {
echo $my_value . PHP_EOL;
}
Adding some number to each element (thus modifying each value):
foreach ($my_array as &$my_value) {
$my_value += 42;
}
If you don't use &$my_value
, then the addition won't have any effect on $my_array
.
But you could write the same not using references:
foreach($my_array as $key=>$value) {
$my_array[$key] = $value + 42;
}
The difference is that we are accessing/changing the original value directly with $my_array[$key]
.
DEMO