PHP combine two associative arrays into one array PHP combine two associative arrays into one array arrays arrays

PHP combine two associative arrays into one array


array_merge() is more efficient but there are a couple of options:

$array1 = array("id1" => "value1");$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);$array4 = $array1 + $array2;echo '<pre>';var_dump($array3);var_dump($array4);echo '</pre>';// Results:    array(4) {      ["id1"]=>      string(6) "value1"      ["id2"]=>      string(6) "value2"      ["id3"]=>      string(6) "value3"      ["id4"]=>      string(6) "value4"    }    array(4) {      ["id1"]=>      string(6) "value1"      ["id2"]=>      string(6) "value2"      ["id3"]=>      string(6) "value3"      ["id4"]=>      string(6) "value4"    }


There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array