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 Replies to “PHP odds! today: pass by reference traps”

  1. 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. 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!

Leave a Reply

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