phparraysmultidimensional-arrayassociative-arrayarray-map

Append an associative element to each row of a 2d array


I have a multidimensional array:

$template = Array (
    [0] => Array ( [id] => 352 [name] => a ) 
    [1] => Array ( [id] => 438 [name] => b ) 
    [2] => Array ( [id] => 351 [name] => c ) 
)

and an array map function

function myfunction()
{
    return "[selected]=>null";
}
print_r(array_map("myfunction",$template));

which results in

Array ( 
   [0] => [selected]=>null 
   [1] => [selected]=>null 
   [2] => [selected]=>null
)

How do I map the array to get this result instead:

Array (  
    [0] => Array ( [id] => 352 [name] => a [selected] => null)  
    [1] => Array ( [id] => 438 [name] => b  [selected] => null)  
    [2] => Array ( [id] => 351 [name] => c  [selected] => null) 
)

Solution

  • You need to add the value to each given array (inside the callback), like:

    <?php
    
    $in = [
        [ 'id' => 352, 'name' => 'a' ],
        [ 'id' => 438, 'name' => 'b' ],
        [ 'id' => 351, 'name' => 'c' ],
    ];
    
    $out = array_map(function (array $arr) {
        // work on each array in the list of arrays
        $arr['selected'] = null;
    
        // return the extended array
        return $arr;
    }, $in);
    
    print_r($out);
    

    Demo: https://3v4l.org/XHfLc