What is the difference between array_merge and array_combine?

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
)

Related Posts

Associative Array in PHP?

An associative array is a simple and very important array of PHP. This array is also used the most, it is very easy to understand this array,…

How to work in functions PHP?

If there is any task in your program which you train to execute repeatedly then instead of writing the code for that task at a different place…

For Loofs in PHP

In for-loop initialization, condition and increment happen on the same line. The loop keeps on repeating as long as the condition is true. When the for loop…

If Else Conditionals in Php?

If Else statement is the most important feature of any programming language, PHP is used to run any Code Of Block according to If Else conditions. This…

What are operators in PHP? PHP – Operator Types

Operators are used to developing data. In Programming Languages, Operators are taken from Mathematics and Operator Programmers work with Data. An operator is a chain of symbols…

String Functions in PHP?

When many characters are written together in sequence, they form a string. For example, India is a string. It is made up of i, n, d, i,…

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