In PHP, array_merge() and array_combine() are used to combine arrays in different ways. Both functions are powerful tools for manipulating arrays, but they behave differently. array_merge() merges arrays together, while array_combine() creates an array using one array for keys and another for values.
// Syntax for merging multiple arrays
array_merge($array1, $array2, ...);
// Syntax for combining keys and values into one array
array_combine($keys, $values);
array_merge() merges one or more arrays into a single array. If the arrays have numeric keys, the values will be appended; if the arrays have associative keys, the values will be overwritten.
// Merge two associative arrays into one
<?php
$array1 = array("a" => "Apple", "b" => "Banana");
$array2 = array("c" => "Cherry", "d" => "Date");
$merged = array_merge($array1, $array2);
print_r($merged);
?>
The function combines both arrays into a new array. Since all keys are unique, no values are overwritten and the output contains all elements.
array_combine() creates a new array by using one array for the keys and another array for the values. Both arrays must have the same number of elements.
// Create an associative array from keys and values
<?php
$keys = array("a", "b", "c");
$values = array("Apple", "Banana", "Cherry");
$combined = array_combine($keys, $values);
print_r($combined);
?>
Each value from the second array is assigned to its corresponding key from the first array. The result is a clean associative array.
? Keys ➡️ Values ➡️ Associative Array
// Visual mapping of array_combine logic
["a","b","c"] + ["Apple","Banana","Cherry"]
=> ["a"=>"Apple","b"=>"Banana","c"=>"Cherry"]
Enter values separated by commas to see the result.
array_merge() when combining datasets or listsarray_combine()