Difference between array_merge() and array_combine() in PHP

array_combine(keys, values)

suppose we have two array, one array contain Name and another array contain age- and we want to create single array with name and age-

so in this case we use array combine - 

a - $fname=array("Ali","Aslam","Raj");
b - $age=array("35","37","43");

Defination - 

array_combine() is used to creates a new array by using the key of one array as keys and using the value of other array as values. One thing to keep in mind while using array_combine() that number of values in both arrays must be same.

$c=array_combine($fname,$age);
print_r($c);

<?php
$fname=array("Ali","Aslam","Raj");
$age=array("35","37","43");

$res=array_combine($fname,$age);
print_r($re);
?>

Result - 

Array ( [Ali] => 35 [Aslam] => 37 [Raj] => 43 )


array_merge(array1, array2, array3, ...)

The array_merge() function merges one or more arrays into one array.

If two or more array elements have the same key, the last one overrides the others.

<?php
$a=array("a"=>"red","b"=>"green");
$b=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>

Result - 

Array ( [a] => red [b] => yellow [c] => blue )



No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...