How to Fix PHP Array Merge vs Plus Operator Confusion
In this tutorial, you'll learn about How to Fix PHP Array Merge vs Plus Operator Confusion. We cover key concepts, practical examples, and best practices.
The Problem
Fix unexpected behavior when using array_merge and the + operator on associative arrays — without proper handling, this issue causes subtle bugs that are hard to trace in production.
Quick Fix
Wrong Code
// WRONG — this approach triggers the php-array-merge-vs-plus error
<?php
\$defaults = ['color' => 'red', 'size' => 'M'];
\$overrides = ['color' => 'blue'];
\$result = \$defaults + \$overrides;
echo 'Color: ' . \$result['color'];
Wrong Output
Color: red
// + operator keeps the first value, not the override!
Right Code
// RIGHT — corrected implementation
<?php
\$defaults = ['color' => 'red', 'size' => 'M'];
\$overrides = ['color' => 'blue', 'weight' => 100];
\$merge = array_merge(\$defaults, \$overrides);
print_r(\$merge);
\$plus = \$defaults + \$overrides;
print_r(\$plus);
\$a = [1 => 'a', 2 => 'b'];
\$b = [1 => 'c', 3 => 'd'];
print_r(array_merge(\$a, \$b));
print_r(\$a + \$b);
Right Output
Array ( [color] => blue [size] => M [weight] => 100 )
Array ( [color] => red [size] => M [weight] => 100 )
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [1] => a [2] => b [3] => d )
Prevention
- Use array_merge for overriding associative arrays (string keys)
- Use + for merging with defaults (keeps first value)
- For numeric keys, array_merge re-indexes; + preserves original keys
- Test edge cases, the behavior difference is a common source of bugs
Common Mistakes with array merge vs plus
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PHP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro