phparraysmultidimensional-arrayarray-mergedefaults

How to merge default values into subarrays of a new multidimensional array?


What is the best way to define a new multidimensional array with default key/value pairs?

I think it's best explained by code sample here:

$defaultOptions = ['foo' => 'bar', 'another' => 'value'];
$mdArray = [
    'first' => [
        'title' => 'I am first',
        $defaultOptions,
    ],
    'second' => [
        'title' => 'I am second',
        $defaultOptions
    ]
];

This produces:

Array 
( 
    [first] => Array 
               ( 
                   [title] => I am first 
                   [0] => Array  
                          ( 
                              [foo] => bar 
                              [another] => value ) 
                          ) 
    [second] => Array 
                ( 
                    [title] => I am second 
                    [0] => Array 
                           ( 
                               [foo] => bar 
                               [another] => value 
                           ) 
                ) 
)

I would like the 0 key to be omitted from $defaultOptions in $mdArray, so that key/value pair would be applied to the same level as where the $defaultOptions is defined.

Is there a way to do it within array definition, or do I have to process this array later and append these $defaultOptions?


Solution

  • You can achieve it in two ways.

    The first option is use + operator:

    $mdArray = [
        'first' => ['title' => 'I am first'] + $defaultOptions,
        'second' => ['title' => 'I am second'] + $defaultOptions
    ];
    

    The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

    http://php.net/manual/en/language.operators.array.php

    The second option is use array_merge() function:

    $mdArray = [
        'first' => array_merge(['title' => 'I am first'], $defaultOptions),
        'second' => array_merge(['title' => 'I am second'], $defaultOptions)
    ];
    

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

    http://php.net/manual/en/function.array-merge.php