The way you do it there is no difference as to the performance. The results will be the same.
The question of whether or not to assign the variable to foreach
will make a difference in the following cases:
- Wish to change the value of the array in
foreach
.
- Foreach
Example:
$range = range(1, 10);
foreach ($range as $key => $value)
{
$range[$key] = $value * 2;
}
Or with reference:
foreach ($range as $key => &$value)
{
$value = $value * 5;
}
When we do in the second case, the $range
shall be amended on account of the reference.
print_r($range);
The exit will be:
[
5,
10,
15,
20,
25,
30,
35,
40,
45,
50,
]
Beware of Foreach References
Just to complement, when you’re using foreach
, take great care, because being reference, the variable that refers the elements of the array
always reference the last element of array
. That is to say:
foreach ($range as $key => &$value)
{
$value = $value * 5;
}
$value = 'Oi, eu sou o Goku';
The exit will be:
[
5,
10,
15,
20,
25,
30,
35,
40,
45,
"Oi, eu sou o Goku",
]
To solve this, you must use the unset
in $value
, to cancel the reference and this does not occur, because maybe you accidentally can create a variable with that name.
Another reference problem with the foreach
is as follows: The last element is as the penultimate value if you do another foreach
(if the second foreach
is without reference):
$range = range(1, 5);
This generates:
[1, 2, 3, 4, 5]
So after that:
foreach ($range as &$value) {}
foreach($range as $value) {};
print_r($range);
The array $range
gets like this:
[1, 2, 3, 4, 4]
I hope you enjoyed the "additional reference tips".
No difference, it’s the same, just changed the syntax.
– rray
Absolutely none, you’d have any difference if
$pdo->query($sql)
were a Generator, what is not the case.Às vezes, parece que o código 1 é mais rápido e às vezes parece que não há diferença alguma.
: benchmarking codes is something reasonably complicated, you will see performance variations in the same code depending even on the position of the planets in the solar system, then I recommend that you understand what rolls under the cloths before you go out rotating and counting seconds of execution.– BrunoRB
Yes, it’s true. So I asked how the PHP interpreter works with both codes. Thank you very much.
– Breno Macena
@Brenomascena major care has to be with the for( ; ), while() etc because if you put something inside, it is processed at every iteration. When in doubt, calling the variable instead of the method avoids having to worry about it.
– Bacco
Yes. I suspected that in the second code foreach ran the query function every time. But that would not make any sense, because in my view the program would not work properly, which is not the case.
– Breno Macena