difference between array_combine and array_merge ?

Question:  difference between array_combine and array_merge ?

array_combine give an array by combining two arrays($keyArray, $valueArray) and both $keyArray & $valueArray must have same number of elements. $keyArrays become keys of returning Array, $valueArray become values of returning Arrays.

array_merge gives an array by merging two array ($array1, $array2) and both can have different number of elements. $array1 and $array2 are added in returning array.

For example :

$first = ['a'=>'one',
             'b'=>'two',
             'c'=>'three'];

$second = ['a'=>'fourth',
        'b'=>'fifth',
        'c'=>'sixth',
        'D'=>'TENTH'];

$a = array_merge($first,$second);
echo '<pre>';
print_r($a);

Output :

Array
(
    [a] => fourth
    [b] => fifth
    [c] => sixth
    [D] => TENTH
)

Array_combine Example

1. There must be Equal no of index in both of the Arrays.

$first = ['a'=>'one',
             'b'=>'two',
             'c'=>'three'];

$second = ['a'=>'fourth',
        'b'=>'fifth',
        'c'=>'sixth',];
$a = array_combine($first,$second);
echo '<pre>';
print_r($a);

Sample output : 

Array
(
    [one] => fourth
    [two] => fifth
    [three] => sixth
)



In case of any confusion feel free to comment!

difference between array_combine and array_merge ? difference between array_combine and array_merge ? Reviewed by Dhaneshwar on 11:46:00 AM Rating: 5

No comments:

Powered by Blogger.