Is using PHP array_merge function the right way to merge associative arrays?

Learn how the PHP array_merge function works and which is the proper method to merge associative arrays?

An associative array is an array of elements with key=>value pairs and looks something like this, array("a" => "blue", "b" => "green"). The keys may be of numeric or non-numeric. There are two ways to merge these arrays.

Say we have two arrays named array1 and array2, then they can be merged with the PHP array_merge() function like,

          array_merge(array1, array2);

or else with the + operator like,

          array1 + array2;

But which one is the right method to use? Well, that purely depends on your requirement.

1. Using array_merge on Associative Array

When we use array_merge function on arrays with non-numeric keys, and if the arrays has duplicate key values, then the last array value will override the first one.

Example
<?php
$colors1 = array("a" => "blue", "b" => "green");
$colors2 = array("b" => "grey", "c" => "purple");
print_r(array_merge($colors1,$colors2));
?>
Output

Array ( [a] => blue [b] => grey [c] => purple )

But for arrays with numeric keys, the function will tend to reset the keys starting from '0'(zero) for the merged array. Hence even in case of duplicate keys, there won't be any value replacement.

Example
<?php
$colors1 = array("1" => "blue", "3" => "green");
$colors2 = array("3" => "grey", "4" => "purple");
print_r(array_merge($colors1,$colors2));
?>
Output

Array ( [0] => blue [1] => green [2] => grey [3] => purple )

Recommended Read: How to use PHP PREG MATCH function to validate Form Input


2. Using Additional Operator (+) on Associative Array

Consider we use the + operator to merge two associative arrays with non-numeric keys. And if there are any duplicate keys, the first array value will be taken for the key omitting the second array value.

Example
<?php
$colors1 = array("a" => "blue", "b" => "green");
$colors2 = array("b" => "grey", "c" => "purple");
print_r($colors1 + $colors2);
?>
Output

Array ( [a] => blue [b] => green [c] => purple )

In case of numeric keys, the + operator won't reset the key values for the merged array. So if we have same keys in both arrays, then the first array value will be taken.

Example
<?php
$colors1 = array("1" => "blue", "3" => "green");
$colors2 = array("3" => "grey", "4" => "purple");
print_r($colors1 + $colors2);
?>
Output

Array ( [1] => blue [3] => green [4] => purple )

If you don't want the numeric keys to be reset, then use the additional (+) operator for merging. In case you have duplicate numeric keys in the arrays and don't want to lose any element, just go for array_merge function.


No comments:

Post a Comment