There's a thing that I don't understand when I use array_merge() :
$defaultOptions = [
'active' => null,
'activeClass' => 'active',
'wrapper' => [
'attributes' => null,
'templateVars' => null
],
'item' => [
'hasChildrenClass' => '', // this disappears after array_merge
'attributes' => null,
'linkAttrs' => null,
'templateVars' => null
]
];
$options = [
'active' => [5,3],
'item' => [
'attributes' => ['class' => 'test']
]
];
$options = array_merge($defaultOptions, $options);
The result of $options is
[
'active' => [
(int) 0 => (int) 5,
(int) 1 => (int) 3,
],
'activeClass' => 'active',
'wrapper' => [
'attributes' => null,
'templateVars' => null,
],
'item' => [
'attributes' => [
'class' => 'test',
],
],
]
I don't understand why $options['item']['hasChildrenClass'] disappeared in my result ?
CodePudding user response:
array_merge
will replace the item
array element with the whole contents from the second array, you would need to use array_merge_recursive
to make sure it merges to all levels.
$option = array_merge_recursive($defaultOptions, $options);
print_r($option);
gives...
Array
(
[active] => Array
(
[0] =>
[1] => 5
[2] => 3
)
[activeClass] => active
[wrapper] => Array
(
[attributes] =>
[templateVars] =>
)
[item] => Array
(
[hasChildrenClass] =>
[attributes] => Array
(
[0] =>
[class] => test
)
[linkAttrs] =>
[templateVars] =>
)
)
(There may be a dupe out there, let me know if this is the case)
CodePudding user response:
In array_merge()
if the arrays have the same string keys, then values from the later arrays will overwrite the previous one. If the arrays have numeric keys, then values from the later arrays will appended with previous one. If the arrays contain null
or empty
values, this value will be skipped and removed from the merged array.