array_merge() and array_combine()

shivv89

In PHP, both array_merge() and array_combine() are used to work with arrays, but they have different purposes. Here’s a breakdown of each function with examples:

array_merge()

  • Purpose: Merges two or more arrays into one. If arrays have the same string keys, the later values will overwrite the earlier ones. If arrays have numeric keys, they will be re-indexed.
  • Example:
$array1 = ['a' => 'apple', 'b' => 'banana'];
$array2 = ['c' => 'cherry', 'd' => 'date'];
$array3 = ['e' => 'elderberry'];

// Merging multiple arrays
$mergedArray = array_merge($array1, $array2, $array3);

print_r($mergedArray);


Output:

Array
(
    [a] => apple
    [b] => banana
    [c] => cherry
    [d] => date
    [e] => elderberry
)

array_combine()

  • Purpose: Creates a new array by combining two arrays — one for the keys and one for the values. The first array will be used as keys, and the second array will be used as values.
  • Example:
$keys = ['a', 'b', 'c'];
$values = ['apple', 'banana', 'cherry'];

// Combining the arrays into a new associative array
$combinedArray = array_combine($keys, $values);

print_r($combinedArray);


Output:

Array
(
    [a] => apple
    [b] => banana
    [c] => cherry
)

Key Differences:

  • array_merge() combines arrays into one larger array, but re-indexes numeric keys and overwrites string keys if duplicates exist.
  • array_combine() creates a new associative array from two arrays — one for the keys and one for the values.

Leave a Comment