What is the difference between array_merge and array_combine?

Posted by

array_merge() Function

 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. it always work with index array and associative array

syntax

array array_merge( $array1, $array2, ...., $array n)

example

<?php
  

$team1 = array("shivam","dharmu sir","raj sir");
  
 
$team2 = array("rahul","roshan","avinash");
  

$team3 = array_merge($team1, $team2);
  
echo "<pre>";
print_r($team3);
echo "</pre>";
  
?>

output

Array
(
    [0] => shivam
    [1] => dharmu sir
    [2] => raj sir
    [3] => rahul
    [4] => roshan
    [5] => avinash
)

array_combine() Function

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, all elements of one array will be the keys of new array and all elements of the second array will be the values of this new array.

syntax

array_combine(array1, array2)

example

<?php
  

$team1 = array("shivam","dharmu sir","raj sir");
  
 
$age = array("20","22","24");
  

$team3 = array_combine($team1, $age);
  
echo "<pre>";
print_r($team3);
echo "</pre>";
  
?>

output

Array
(
    [shivam] => 20
    [dharmu sir] => 22
    [raj sir] => 24
)

Difference b/w array_merge() and array_conbine()-

S.Narray_merge()array_combine()
1This function merges the two or more arrays.This array combine only two arrays.
2This function merges  the arrays such that all the arrays have keys and values.containing keys and another array containing values.
3The arrays are appended at the end of the first array.The arrays are combined.
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x