3 ms·
Wasn't this a given when working with PHP? You can afterall send the reference so that you are modifying the array as you go, rather than at the end. $array =
by francispelland 14y ago
Wasn't this a given when working with PHP? You can afterall send the reference so that you are modifying the array as you go, rather than at the end.
$array = array(1,2,3,4,5);
foreach ($array as &value){...}
- narcissus 14y agoJust always be sure to unset $value afterwards :)
- xkcdfanboy 14y agoI can't count the times that references have caused wierd errors in my PHP code. Definitely a good recommendation.
- narcissus 14y agoI hear ya. In fact, I got burned by that problem enough times to make a test for it in my PHPCS 'coding standard'... which is basically a handful of standards that look for my stupid, repeated, coding errors :)
- function_seven 14y agoMy own standard is this: foreach ($array as & $ref) { // Do something with $ref } unset ($ref); i.e. put the `unset()` call on the same line as the closing brace, forever "welding" it to that block.
- Kiro 14y agoWhy do you even use references in the first place?
- smsm42 14y agoData structures like trees, etc. are pretty hard to do without them, due to default array by-value semantics.
- notJim 14y agoHuh, I've never actually had that problem, but that's a really good point.
- ufo 14y agoI don't know PHP. What happens if you forget to unset the reference?
- uxp 14y agoThen you get the joy of being able to play with it later. $array = array(1,2,3,4,5); foreach ($array as &$value) { echo $value; // some non-mutating action } $value = 'woops'; print_r($array); // ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => woops)
- jtreminio 14y agoThat's why I tell the developers on my team that if they're thinking of using references in PHP, then they're probably Doing It Wrong.
- smsm42 14y agoUnless they are experienced developers doing complex data structures, this is probably a good advice. References need to be approached very carefully to use them right. It doesn't help that in old PHP versions you had to use references when working with objects, and some people assumed some bad habits from those times and these habits propagate through code without people actually understanding what's going on.
- dools 14y agoA more "hair friendly" way to modify an array from within a foreach loop is to just use the array key: foreach($array as $key => $value) { if(someCondition($key)) $array[$key] = someTransformation($value); } or whatever - ie. just use the key to modify the original array directly. It's much easier to read and see what's happening (in my opinion anyway).