What is the difference between array_merge() and array_merge_recursive() in php?
array_merge() | array_merge_recursive() |
---|---|
This function is used to join one or more arrays into a single array. | Used to merge multiple arrays in such a manner that values of one array are appended to the end of the previous array. |
Syntax: array_merge($array1, $array2, $array3...); | Syntax: array_merge_recursive($array1, $array2, $array3...); |
If we pass a single array, it will return re-indexed as a numeric array whose index starts from zero. | If we pass a single array, it will return re-indexed in a continuous manner. |
BY Best Interview Question ON 07 Apr 2020
Example
Example of an array_merge() function:
$arrayFirst = array("Topics" => "Maths","Science", "Computers");
$arraySecond = array("Class-V", "Class-VI", "Section"=>"C");
$resultArray = array_merge($arrayFirst, $arraySecond);
print_r($resultArray);
Output
Array ( [Topics] => Maths [0] => Science [1] => Computers [2] => Class-V [3] => Class-VI [Section] => C )
Example of an array_merge_recursive() function with all different keys:
$a1=array("a"=>"Best", "b"=>"Interview");
$a2=array("z"=>"Question");
print_r(array_merge_recursive($a1, $a2));
Output
: Array
(
[a] => Best
[b] => Interview
[z] => Question
)