title: How to merge two multidimensional arrays without overwriting existing keys in PHP?
body: <p>I'm trying to add two multidimensional arrays. The function should be the exact same as adding the arrays together like so: $new_array = $array1 + $array2, except it should work with multidimensional arrays. This means that $array2 should not overwrite existing key values.</p>
  
  <p>Example: let's say I have the following $default_array:</p>
  
  <pre><code>array
    'something' =&gt; int 0
    'nested' =&gt; 
      array (size=3)
        'a' =&gt; null
        'b' =&gt; null
        'c' =&gt; null
  </code></pre>
  
  <p>And the following $user_array:</p>
  
  <pre><code>array
    'something' =&gt; int 1000
    'nested' =&gt; 
      array (size=3)
        'a' =&gt; 1
    'new' =&gt; int 4
  </code></pre>
  
  <p>Adding the two together (like $user_array + $default_array) should give me:</p>
  
  <pre><code>array (size=4)
        'something' =&gt; int 1000
        'nested' =&gt; 
          array (size=3)
            'a' =&gt; 1
            'b' =&gt; null
            'c' =&gt; null
        'new' =&gt; int 4
  </code></pre>
  
  <p>Currently, it seems that if I add the two multidimensional arrays, the overwriting feature seems to only apply to the first array dimension. This means that in this case, 'nested' already exists in the $user_array, so it wouldn't append the other values.</p>
  
  <p>EDIT: I should also mention that this would need to work with unlimited amount of dimensions.</p>
  
  <p>EDIT 2: I just tried to apply Rain's answer, and it's not working as intended. First off, I'm getting "undefined index" notices. Secondly, the output it not as I wanted. Consider the following arrays:</p>
  
  <pre><code>        $default = array(
              'a' =&gt; array(
                  'a' =&gt; 'a',
                  'b' =&gt; 'b',
                  'c' =&gt; 'c',
                  ),
              );
  
          $user = array(
              'b' =&gt; 1,
              'a' =&gt; array(
                  'b' =&gt; 'something',
                  'c' =&gt; 'something else',
                  'd' =&gt; 'd',
                  ),
              'c' =&gt; 2);
  </code></pre>
  
  <p>The output I'm getting with Rain's function is this:</p>
  
  <pre><code>array (size=3)
    'a' =&gt; 
      array (size=3)
        'a' =&gt; string 'a' (length=1)
        'b' =&gt; string 'b' (length=1)
        'c' =&gt; string 'c' (length=1)
    'b' =&gt; int 1
    'c' =&gt; int 2
  </code></pre>
  
  <p>In this example, the 'b' and 'c' keys in the sub-array should be 'something' and 'something else', respectively. I'm not quite sure how to fix that.</p>