skip to Main Content

I have two arrays to join each other:

$array_1 = array(18 => 0
 , 19 => 0
 , 20 => 0
 , 21 => 0
 , 22 => 0
 , 23 => 0);

$array_2 = array(22 => 3
 , 23 => 4);

var_dump(array_merge($array_1, $array_2));

The result from this code:

array(8) { [0]=> int(0) 
 [1]=> int(0) 
 [2]=> int(0) 
 [3]=> int(0) 
 [4]=> int(0) 
 [5]=> int(0) 
 [6]=> int(3) 
 [7]=> int(4) }

The result I expect:

array(8) { [18] => int(0)
, [19] => int(0)
, [20] => int(0)
, [21] => int(0)
, [22] => int(3)
, [23] => int(4), }

How I can get expected results?

2

Answers


  1. You can use union of two arrays in good order :

    $array_1 = array(18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0);
    $array_2 = array(22 => 3, 23 => 4);
    var_dump($array_2 + $array_1);
    
    Login or Signup to reply.
  2. From the manual:

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

    So simply convert the array keys to strings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search