RSS Feed
^__^

PHP odds! today: pass by reference traps

,

This is dangerous:

//example array
$array = array('a' => array(array(243,453,435,232)));

foreach ($array['a'] as &$value) {
         $value[3] = $newvalue;
}

This works, but now the $value var is in the array by reference which can lateron lead to:
Notice: Array to string conversion
EDIT:
see below in the comments for when…

This works better:

Using reference, array_walk und lambda functions works:

array_walk($array[$key], function(&$value, $key, $newvalue) {
                                   $value[3] = $newvalue;
                          },$newvalue);
//works

or that (thanks lars):

foreach ($array['a'] as $k => $value) {
         $array['a'][$k][3] = $newvalue;
}

4 responses to “PHP odds! today: pass by reference traps”

  1. Lars says:

    The first code sample doesn’t make any sense. $value[4] while $value is 0?! You either mean $array[$key][4] = $newvalue; or foreach ($array as $k => &$v)…

  2. Ivo Bathke says:

    yep youre right
    the code was incomplete

    the problem was actually this:

    $array = array('a' => array(array(243,453,435,232)));
     
    foreach ($array['a'] as &$value) {
             $value[3] = 'aa';
    }
    var_dump($array);
    
    foreach ($array as $value) {
        var_dump($value);
          foreach ($value as $e) {
              var_dump($e);
               echo implode(',', $e);
         }
    }
    

    the problem here is that the second $value is due to the “reference” in the first loop somehow “occupied” with the reference and not newly set, as i thought

    so this works:

    $array = array('a' => array(array(243,453,435,232)));
     
    foreach ($array['a'] as &$value) {
             $value[3] = 'aa';
    }
    var_dump($array);
    
    foreach ($array as $v) {
        var_dump($v);
          foreach ($v as $e) {
              var_dump($e);
               echo implode(',', $e);
         }
    }
    

    all this trouble because of my lazyness to write some chars more
    the longer way works of course, as you proposed:

    foreach ($array['a'] as $k => $value) {
             $array['a'][$k][3] = $newvalue;
    }
    

    Lunchbreak!

  3. Max Girkens says:

    wusste gar nicht dass das geht mit der Referenz in der foreach Schleife. Seit welcher Version gibt’s das denn?

    Die Merkwürdigkeit scheint aber auch schon anderen passiert zu sein…

  4. Lars says:

    Ach, jetzt versteh ich auch, was dein Problem ist!

    Ja, die Variablen-Referenz bleibt auch bei reference nach der foreach bestehen, siehe entsprechende Warnung im PHP Manual: http://php.net/manual/en/control-structures.foreach.php

    Also einfach ein unset() zwischen die zwei foreach schieben und gut.

Leave a Reply

Your email address will not be published. Required fields are marked *