Search code examples
phparraysmerging-data

Merge two indexed arrays without overwriting elements in first array


I'm trying to merge two arrays for the values of array1 that are set

Array1 ( [0] => false [1] => 200 )
Array2 ( [0] => true [1] => 80 [2] => 60 [3] => 75 [4] => 50 [5] => 0 [6] => 0 [7] => 30 [8] => 40 ) 

for instance result array:

Array3 ( [0] => false [1] => 200 [2] => 60 [3] => 75 [4] => 50 [5] => 0 [6] => 0 [7] => 30 [8] => 40 ) 

What would be an efficient way to handle this.


Solution

  • Use the array union operator.

    $array3 = $array1 + $array2;