June 5, 2025
What’s the difference between array_merge() and + when combining arrays?
🔹 array_merge()
:
- Reindexes numeric keys.
- Overwrites string keys with values from later arrays.
$a = [0 => 'apple', 1 => 'banana'];
$b = [1 => 'orange', 2 => 'grape'];
print_r(array_merge($a, $b));
Result:
[0 => 'apple', 1 => 'orange', 2 => 'grape']
🔹 $a + $b
(Union operator):
- Preserves keys from the left-hand array (
$a
) - Does not overwrite any existing keys.
$a = [0 => 'apple', 1 => 'banana'];
$b = [1 => 'orange', 2 => 'grape'];
print_r($a + $b);
Result:
[0 => 'apple', 1 => 'banana', 2 => 'grape']
📌 Interview Tip: Use +
when merging with preserved keys; use array_merge()
when you want values merged and reindexed.
Comments are closed.