The way you do there is no difference in performance. The results will be the same.
The question of assigning or not the variable to iterate it with foreach
will make a difference in the following cases:
- I want to change the array value in
foreach
.
- Foreach with reference
Example:
$range = range(1, 10);
foreach ($range as $key => $value)
{
$range[$key] = $value * 2;
}
Or even with reference:
foreach ($range as $key => &$value)
{
$value = $value * 5;
}
When we do in the second case, the $range
will be changed by reference.
print_r($range);
The output will be:
[
5,
10,
15,
20,
25,
30,
35,
40,
45,
50,
]
Beware of References in Foreach
Just to complement, when you use reference in foreach
, be very careful, because being a reference, the variable that references the elements of array
will always refer to the last element of array
. That is:
foreach ($range as $key => &$value)
{
$value = $value * 5;
}
$value = 'Oi, eu sou o Goku';
The output will be:
[
5,
10,
15,
20,
25,
30,
35,
40,
45,
"Oi, eu sou o Goku",
]
To solve this, you should use unset
in $value
, to undo the reference and it does not happen, because you might accidentally create a variable just by that name.
Another problem of the reference with foreach
is as follows: The last element becomes the value of the penultimate if you make another foreach
(if the second foreach
is without reference):
$range = range(1, 5);
This generates:
[1, 2, 3, 4, 5]
Then after that:
foreach ($range as &$value) {}
foreach($range as $value) {};
print_r($range);
The array $range
looks like this:
[1, 2, 3, 4, 4]
I hope you enjoyed the "additional reference tips".