phparray-walk

array_walk not changing value


function values($id,$col)
{
     $vals = [1=>['name'=>'Lifting Heavy Boxes']];
     return $vals[$id][$col];
}
$complete = [1=>["id"=>"2","sid"=>"35","material_completed"=>"1","date"=>"2017-12-18"]];
$form = 'my_form';

array_walk($complete, function(&$d,$k) use($form) {
    $k = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
    echo 'in walk '.$k."\n";
});
print_r($complete);

the echo outputs:

in walk Lifting Heavy Boxes [12/18/17] (my_form)

the print_r outputs:

Array
(
    [1] => Array
        (
            [id] => 2
            [sid] => 35
            [material_completed] => 1
            [date] => 2017-12-18
        )

)

I have another array walk that is very similar that is doing just fine. The only difference I can perceive between them is in the one that's working, the value $d is already a string before it goes through the walk, whereas in the one that's not working, $d is an array that is converted to a string inside the walk (successfully, but ultimately unsuccessfully).

Something I'm missing?

And here's the fixed version:

array_walk($complete, function(&$d,$k) use($form) {
    $d = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
});

That's what I was trying to do anyway. I wasn't trying to change the key. I was under the mistaken impression that to change the value you had to set the key to the new value.


Solution

  • You cannot change the key of the array inside the callback of array_walk():

    Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

    This is also mentioned in the first comment:

    It's worth nothing that array_walk can not be used to change keys in the array. The function may be defined as (&$value, $key) but not (&$value, &$key). Even though PHP does not complain/warn, it does not modify the key.