Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Unexpected array_merge_recursive() output

I have this code

$a1 = array(
    'success'    => TRUE,
    'data'       => array(
        'foo' =>
        array(
            21 =>
            array(
                1 =>
                array(1, 2, 3, 4, 5)
            )
        )
    )
);

$a2 = array(
    'success'    => TRUE,
    'data'       => array(
        'foo' =>
        array(
            21 =>
            array(
                7 =>
                array(6, 7, 8, 9, 10)
            )
        )
    )
);

$results = array();
$results = array_merge_recursive($results, $a1['data']);
$results = array_merge_recursive($results, $a2['data']);
var_dump($results);

From what I understood of array_merge_recursive(), I am expecting the results would be

array
  'foo' => 
    array
      21 => 
        array
          1 => 
            array
              0 => int 1
              1 => int 2
              2 => int 3
              3 => int 4
              4 => int 5
           7 =>
              0 => int 6
              1 => int 7
              2 => int 8
              3 => int 9
              4 => int 10

Instead I get this

array
  'foo' => 
    array
      21 => 
        array
          1 => 
            array
              0 => int 1
              1 => int 2
              2 => int 3
              3 => int 4
              4 => int 5
      22 => 
        array
          7 => 
            array
              0 => int 6
              1 => int 7
              2 => int 8
              3 => int 9
              4 => int 10

Where did the 22 index come from? Why is it outputting differently? Did I use the function wrong?

like image 739
developarvin Avatar asked Jun 01 '26 07:06

developarvin


1 Answers

array_merge_recursive merges elements/arrays from the same depth as the first array, but if both arrays the key is a numerical index and they are the same it then appends to it. This is what is happening in your situation. since then your array is appended at 2nd level where index 21 is found by creating index 22. To receive the desired output you have change your index 21 to a string key like "x21"

Notes from php manual

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

like image 55
DevZer0 Avatar answered Jun 03 '26 22:06

DevZer0