Skip to content
array_merge vs arrat_combine

Difference between array_merge() and array_combine() in PHP

array_merge()

Syntax : array_merge(array1, array2...): array

The array_merge() function merges the elements of one or more arrays into a single resultant array in such a way, So that the values of one array append to the end of previous ones. We can pass one or more arrays as parameters.

Example :

<?php
  $array1 = array(1, 'a' => "white", 10, 'b' => "apple");
  $array2 = array('a' => "red", 2, 'xyz', 4, 'b' => "apple");
  $result = array_merge($array1, $array2);
  print_r($result);
?>

Output :

Array ( [0] => 1 [a] => red [1] => 10 [b] => apple [2] => 2 [3] => xyz [4] => 4 )

Note :

  • If the arrays have same string keys, then the value of last array for that key will overwrite the value of previous ones.
  • If the arrays contain numeric keys, then the values of last array will not overwrite the values of previous arrays and will be append on last of the resultant array.
  • If there is only one array with numeric keys, Then the key of resultant array will be re-indexed and start from 0.

array_combine

Syntax : array_combine(array $keys, array $values): array

The array_combine() function creates an array by using the elements from one “keys” array and one “values” array.

While passing two arrays in the function, make sure the number of elements in both the arrays are equal, otherwise it will return an error.

Example :

<?php
  $name=array("Ikhlaque Ahmed","Raheel","Subhan");
  $age=array("35","29","10");

  $combine_array = array_combine($name,$age);
  print_r($combine_array);
?>

Output :

Array ( [Ikhlaque Ahmed] => 35 [Raheel] => 37 [Subhan] => 43 )

Conclusion

We learn today array_merge vs array_combine. This is most asking question on PHP interview. This article will help you to understand better about differences between array_merge vs array_combine.