Hacker News new | past | comments | ask | show | jobs | submit login

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){...}




A 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).


Just always be sure to unset $value afterwards :)


I don't know PHP. What happens if you forget to unset the reference?


Then 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)


That'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.


Unless 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.


Huh, I've never actually had that problem, but that's a really good point.


I can't count the times that references have caused wierd errors in my PHP code. Definitely a good recommendation.


I 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 :)


My 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.


Why do you even use references in the first place?


Data structures like trees, etc. are pretty hard to do without them, due to default array by-value semantics.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: