Performance
I am not an expert on this subject, but I can guarantee that the performance in this case does not make so much difference to the point of just choosing one or the other because of that.
Security - Understanding the behavior of one and the other
The only security that is at risk is yours. I say this because it is necessary to understand the behavior of references in this case.
How did you respond in this question there is a small variation, compared to what is expected of a normal foreach, relative to the variable passed by reference.
In short: The last value is always referenced, which can cause you problems if you override the value of $value
.
$array = [1, 2, 3];
foreach ($array as $key => &$value) {
$value = $value . 'R$';
}
$value = null;
This would generate:
['1R$', '2R$', null]
See an example on IDEONE
So after using a foreach
with reference, it is always good to call unset
in the referenced variable (after the loop).
I'm not going to talk about this much here, because the linked question has a lot on it.
In this case, I'm not telling you not to do this (I've done it a few times). I'm just warning you that you should know all about it, for which "you do not know" cause you problems.
But, noting that a "new behavior" may occur in relation to the first foreach
- and at the same time, this can also affect readability if you neglect to treat the reference variable properly - I could think of your second option as being the best.
$array = [1, 2, 3];
foreach ($array as $key => $value) {
$array[$key] = $value . 'R$';
}
But you need to know if it is necessary and if it is wise to change the original value of your array
. If you are sure that you will no longer use the "% original"%, then you can do this without fear of being happy: p
The disadvantage of reference with array
Remembering that you also have a drawback when using foreach
with reference: You can only loop with foreach
saved in variables. Arbitrary expressions can not be used with reference to some versions of PHP prior to 5.5.
Example:
// Certo:
$array = [];
foreach ([1, 2, 3, 4] as $key => $value) {
$array[$key] = $value . 'R$';
}
// Errado: Isso vai gerar um erro caso use PHP 5.4
foreach ([1, 2, 3, 4] as $key => &$value) {
$value = $value . 'R$';
}
See a small test
Draw your own conclusion
I do not want to give you an opinion on the subject, I want you to just understand that doing a foreach with reference and doing a reassignment with the array
keys may seem like the same thing, but technically it is not. References can be villainous if they are not used wisely. Similarly, overwriting a value of foreach
may not be a good idea if you want to keep the original values.
I'm showing you some points, because this "good practice" thing is actually quite personal. It's always best to know what you're doing and know how to use it on time.