Search code examples
phpindexingarray-merge

Merge 2 arrays: don't change indexes and add the 2nd values in order in the gaps


I have two arrays. I want that I do not change the indexes of the first one and that the second one, is added by order in the gaps of the missing indexes:

$a = array(
     0 => 9,
     2 => 13
     );

$b = array(
     1 => 10,
     2 => 11,
     3 => 12,
     4 => 1
     );

I want this result:

$ab = array(
      0 => 9, 
      1 => 10, 
      2 => 13, 
      3 => 11, 
      4 => 12, 
      5 => 1
      );

I tried this:

$ab = $a+$b;    // Keeps indexes, but removes key 2 from array $ b
$ab = array_merge($a, $b);  // Change indexes
$ab = array_unique(array_merge($a,$b));     // Change indexes
$ab = array_merge($a, array_diff($b, $a));  // Change indexes

Solution

  • Loop through $b, copying the elements to $a. But if the index already exists, increment an adjustment to get the new index.

    function mergeArrays($a, $b) {
        $adjust = 0;
        foreach ($b as $i => $val) {
            while (isset($a[$i + $adjust])) {
                $adjust++;
            }
            $a[$i + $adjust] = $val;
        }
        ksort($a); // Put in order by new indexes
        return $a;
    }
    

    DEMO