What is the difference between array_merge and array_combine?

Posted by

The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that is needed to be merged and returns a new array with merged values of arrays passed in the parameter.

array_merge()

Syntax:

array array_merge( $array1, $array2)

 array1 is the first array with keys and array2 is the second array with the values.

<?php
  
    $array1 = array("subject1" => "Aajay","subject2" => "Vijay");
  
    $array2 = array("subject3" => "Sanjay","subject4" => "Jay");
  
    $final = array_merge($array1, $array2);

    print_r($final);
  
?>

Output:-

Array
(
    [subject1] => Ajay
    [subject2] => Vijay
    [subject3] => Sanajy
    [subject4] => Jay
)

array_combine()

The array_combine() function is used to combine two arrays and create a new array by using one array for keys and another array for values i.e. all elements of one array will be the keys of the new array and all elements of the second array will be the values of this new array.

Syntax:

array_combine(array1, array2)

Example: 

<?php
  
   // Define array1 with keys 
   $array1 = array("subject1" ,"subject2");
  
   // Define array2 with  values
   $array2 = array( "Vijay", "Ram");
  
   // Combine two arrays
   $final = array_combine($array1, $array2);
  
   // Display merged array
   print_r($final);
  
?>

Output:-

Array
(
    [subject1] => Vijay
    [subject2] => Ram
)

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x