Search code examples
phparraysmultidimensional-arrayarray-merge

array_merge removes a empty string


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 ?


Solution

  • 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.

    Read more at php.net manual