PHP Functions - array_merge() and array_combine()

September 10, 2016
PHP has lots of built-in functions. So that you may not remember all the the functions. Among those functions, array_merge and array_combine are 2 very useful php functions that are very useful for core php programmer.

array_merge() function:

array_merge() is a built-in php function that is used to merge two or more arrays in one place. Unlike array_combine, it does not need equal number of elements in the each array. Here is a simple example of array_merge();

Example
<?php
$data1 = array("id"=>"21","name"=>"RKA","contact"=>"9843XXXXXX");
$data2 = array("address"=>"Kathmandu, Nepal");
$arrayMerge = array_merge($data1,$data2);
print_r($arrayMerge);

?>

Output
Array ( [id] => 21 [name] => RKA [contact] => 9843XXXXXX [address] => Kathmandu, Nepal )


array_combine() function: 


array_combine() is also a built-in php function which is used for combine only 2 arrays. And both the array of parameters must have equal number of elements. In fact, array_combine function combines 2 array together and generates index array.

Example: 
<?php
$data3 = array("1","3","5","7");
$data4 = array("a","c","e","g");
$arrayCombine1 = array_combine($data3,$data4);
print_r($arrayCombine1);
?>

Output:
Array ( [1] => a [3] => c [5] => e [7] => g )
Previous
Next Post »