Skip to content

How to Fix PHP Array Merge vs Plus Operator Confusion

DodaTech Updated 2026-06-24 2 min read

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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

### How does array_merge handle numeric vs string keys?

String keys: later values overwrite earlier ones. Numeric keys: values are appended and re-indexed. The + operator keeps the first occurrence regardless of key type.

When should I use array_replace instead?

array_replace overwrites both string and numeric keys without re-indexing. Use it for consistent overwrites.

Which is faster, array_merge or +?

The + operator is faster because it is a language construct, not a function call.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro