Php

Merging two arrays with the array union operator How does it work

20 September 2026 · 10 min read

Merging two arrays with the  array union operator How does it work

Understanding how to manipulate arrays is crucial for any programmer, and PHP offers various methods for combining them. One such method is using the “+” operator, often referred to as the array union operator. This operator provides a simple way to merge two arrays, but it’s essential to grasp its specific behavior to avoid unexpected results. Unlike array_merge(), which re-indexes numeric keys, the “+” operator preserves the keys from the left-hand array. This means if a key exists in both arrays, the value from the left-hand array will take precedence. This article will delve into the intricacies of using the “+” operator for merging arrays, exploring its functionality, use cases, and potential pitfalls. We’ll cover everything from basic syntax to more complex scenarios involving different data types and key structures, providing you with a comprehensive understanding of this powerful tool.

Understanding the “+” Array Union Operator in PHP

The “+” operator in PHP is designed to perform an array union operation. It takes two arrays as operands and returns a new array that contains the elements of both. However, it’s crucial to understand how this operator handles keys. If a key exists in both the left and right operands, the element from the left operand is retained, and the element from the right operand with the same key is discarded. This behavior is different from functions like array_merge(), which can overwrite or re-index keys depending on the array structure. According to the PHP documentation [^1^][https://www.php.net/manual/en/language.operators.array.php], the “+” operator prioritizes keys from the left-hand array, ensuring that their associated values are preserved in the resulting array.

Consider this example: If $array1 = [‘a’ => 1, ‘b’ => 2] and $array2 = [‘b’ => 3, ‘c’ => 4], then $array1 + $array2 will result in [‘a’ => 1, ‘b’ => 2, ‘c’ => 4]. Notice that the value of ‘b’ remains 2, the value from $array1, and the ‘c’ key with its value of 4 is added from $array2. This simple example highlights the core functionality of the “+” operator. It’s particularly useful when you want to combine arrays while giving precedence to the values in the first array. Understanding this key preservation behavior is essential for predicting and controlling the outcome of array merging operations.

The array union operator works differently with numeric keys. If both arrays contain numeric keys, the “+” operator will treat them differently than string keys. The + operator will append the values of the second array to the first, unless it finds the same index. In that case, the value from the first array will be used. In this case, consider this example: If $array1 = [1, 2, 3] and $array2 = [4, 5, 6], then $array1 + $array2 will result in [1, 2, 3], whereas if $array1 = [0 => 1, 1 => 2, 2 => 3] and $array2 = [0 => 4, 1 => 5, 2 => 6], then $array1 + $array2 will result in [0 => 1, 1 => 2, 2 => 3]. It’s important to remember that the + operator will only append values from the right-hand array if the index does not exist in the left-hand array.

Practical Examples of Using the “+” Operator

The “+” operator shines in scenarios where you need to combine configuration settings or default values. Imagine you have a base configuration array and want to allow users to override specific settings. You can use the “+” operator to merge the user’s settings with the base configuration, ensuring that the base settings are used as defaults and the user’s settings take precedence where they overlap. This is a common pattern in web applications and frameworks where flexibility and customization are paramount. For example, consider a scenario where you have default website settings and want to allow users to customize their experience. You can merge two arrays using the “+” operator, with the default settings as the left-hand array and the user’s settings as the right-hand array.

Here’s a code snippet illustrating this:

<?php $default_settings = [ 'theme' => 'default', 'language' => 'en', 'timezone' => 'UTC' ]; $user_settings = [ 'theme' => 'dark', 'language' => 'fr' ]; $merged_settings = $default_settings + $user_settings; print_r($merged_settings); ?> 

The output will be:

Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => default [language] => en [timezone] => UTC ) Array ( [theme] => dark [language] => fr ) Array ( [theme] => dark [language] => fr [timezone] => UTC ) 

In this case, the theme and language settings from the $user_settings array override the default settings. If the $user_settings array does not contain a value for a key in the $default_settings array, then that key and value will be present in the final array. This showcases how the “+” operator can be effectively used to manage configuration options in a flexible and maintainable way.

Key Differences Between “+” and array_merge()

While both the “+” operator and the array_merge() function are used to combine arrays in PHP, their behavior differs significantly, especially when it comes to handling keys. Understanding these differences is crucial for choosing the right tool for the job. The “+” operator prioritizes keys from the left-hand array, effectively ignoring any values associated with duplicate keys in the right-hand array. In contrast, array_merge() handles keys differently. If both arrays have string keys, array_merge() will overwrite the value of the left-hand array’s key with the value of the right-hand array’s key. If the keys are numeric, array_merge() will re-index the keys, potentially leading to unexpected results if you rely on specific numeric keys.

Featured Snippet: The core difference lies in key handling. The “+” operator preserves keys from the left array, discarding values from the right array if keys collide. array_merge(), on the other hand, overwrites string keys from the left array with those from the right and re-indexes numeric keys. Choose the “+” operator when you want to prioritize values from the first array and retain its key structure. Opt for array_merge() when you need to combine arrays and potentially overwrite values based on key collisions or re-index numeric keys.

Here’s a table summarizing the key differences:

  • "+" Operator: Preserves keys from the left-hand array; discards values from the right-hand array if keys collide.
  • array_merge(): Overwrites string keys from the left-hand array with values from the right-hand array; re-indexes numeric keys.

Consider this example:

<?php $array1 = ['a' => 'apple', 'b' => 'banana']; $array2 = ['b' => 'blueberry', 'c' => 'cherry']; $union = $array1 + $array2; $merge = array_merge($array1, $array2); echo "Union: "; print_r($union); echo ""; echo "Merge: "; print_r($merge); echo ""; ?> 

The output will be:

Union: Array ( [a] => apple [b] => banana [c] => cherry )  Merge: Array ( [a] => apple [b] => blueberry [c] => cherry )  

As you can see, the “+” operator retained the ‘banana’ value for key ‘b’ from $array1, while array_merge() overwrote it with ‘blueberry’ from $array2. Choosing the right method depends entirely on your desired outcome and the structure of your arrays. Understanding these distinctions is vital for writing robust and predictable PHP code [^2^][https://www.php.net/manual/en/function.array-merge.php].

Best Practices and Potential Pitfalls

When working with the “+” operator, it’s crucial to be mindful of potential pitfalls and adhere to best practices to ensure your code behaves as expected. One common mistake is assuming that the “+” operator will always append elements from the right-hand array. As we’ve seen, this is only true for keys that don’t already exist in the left-hand array. Always consider the key structure of your arrays before using the “+” operator to avoid unexpected data loss. Another important consideration is the data types of the values being merged. While the “+” operator will generally handle different data types without issue, you should be aware of potential type coercion or unexpected behavior if you’re merging arrays with mixed data types.

Here are some best practices to keep in mind:

  1. Understand Your Data: Before using the “+” operator, analyze the key structure and data types of your arrays to predict the outcome.
  2. Use Descriptive Variable Names: Use clear and descriptive variable names to improve code readability and maintainability.
  3. Test Thoroughly: Test your code with various scenarios to ensure it behaves as expected, especially when dealing with complex array structures.
Infographic here
One potential pitfall is relying on the "+" operator for tasks that are better suited for other array functions. For example, if you need to merge arrays and overwrite values based on key collisions, array\_merge() is a more appropriate choice. Similarly, if you need to combine arrays and remove duplicate values, functions like array\_unique() or array\_intersect() might be more suitable. Always consider the specific requirements of your task and choose the most appropriate tool for the job. According to a Stack Overflow survey \[^3^\]\[https://stackoverflow.com/questions/tagged/php\], a common source of errors in PHP code is misunderstanding the behavior of array functions. By carefully considering the key structure and data types of your arrays, and by choosing the right array function for the task, you can avoid many common pitfalls and write more robust and maintainable code. Remember to document your code clearly, explaining the purpose of each array operation and the expected outcome. This will make it easier for you and others to understand and maintain your code in the future. Consider using an IDE or code editor with debugging capabilities to step through your code and inspect the values of your arrays at each step. This can help you identify and fix errors more quickly and efficiently. [Example:
$test = array('hi'); $test += array('test', 'oh'); var_dump($test); 

Output:

array(2) { [0]=> string(2) "hi" [1]=> string(2) "oh" } 

What does + mean when used on arrays in PHP?

Quoting from the PHP Manual on Language Operators

> The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

So if you do

$array1 = ['one', 'two', 'foo' => 'bar']; $array2 = ['three', 'four', 'five', 'foo' => 'baz']; print_r($array1 + $array2); 

You will get

Array ( [0] => one // preserved from $array1 (left-hand array) [1] => two // preserved from $array1 (left-hand array) [foo] => bar // preserved from $array1 (left-hand array) [2] => five // added from $array2 (right-hand array) ) 

So the logic of + is equivalent to the following snippet:

$union = $array1; foreach ($array2 as $key => $value) { if (false === array_key_exists($key, $union)) { $union[$key] = $value; } } 

If you are interested in the details of the C-level implementation head to

- php-src/Zend/zend_operators.c

-–

Note, that + is different from how array_merge() would combine the arrays:

print_r(array_merge($array1, $array2)); 

would give you

Array ( [0] => one // preserved from $array1 [1] => two // preserved from $array1 [foo] => baz // overwritten from $array2 [2] => three // appended from $array2 [3] => four // appended from $array2 [4] => five // appended from $array2 ) 

See linked pages for more examples.](<https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08 Question & Answer :

I have some code that appears to merge the data from two arrays using +=, but it doesn>)