Beginner LevelPHP 8+
What is the difference between array_merge($a, $b) and the array union operator ($a + $b)?
❓ Interview Prompt: Compare array_merge() vs the + array union operator regarding key overwriting and numeric key re-indexing.
Merging two associative or indexed arrays in PHP can be done using 'array_merge()' or the '+' union operator, but their duplicate key resolution logic is opposite:
1. 'array_merge($a, $b)':
•
Associative String Keys: If '$a' and '$b' share the same string key, the value from '$b' overwrites '$a'.
•
Numeric Keys: Numeric keys are re-indexed sequentially starting from 0, appending values from '$b' to '$a'.
2. Array Union Operator ('$a + $b'):
•
Associative String Keys: If '$a' and '$b' share the same string key, the value from '$a' is PRESERVED, and '$b' is ignored!
•
Numeric Keys: Numeric keys are NOT re-indexed. If key '0' exists in '$a', key '0' from '$b' is discarded.
Code Implementation Example
php
<?php
$a = ['color' => 'red', 0 => 'apple'];
$b = ['color' => 'blue', 0 => 'banana', 1 => 'cherry'];
// 1. array_merge() overwrites string keys and re-indexes numeric keys
$merged = array_merge($a, $b);
// Result: ['color' => 'blue', 0 => 'apple', 1 => 'banana', 2 => 'cherry']
// 2. + Union operator preserves first array's keys and retains numeric keys
$union = $a + $b;
// Result: ['color' => 'red', 0 => 'apple', 1 => 'cherry']💡Comparing array_merge() overwriting vs + array union operator key preservation.
🎯 Interview Key Takeaway
array_merge() overwrites string keys with the second array and re-indexes numeric keys; + preserves the first array's keys.
#Arrays#array_merge#Union Operator#Beginner
Back to all PHP 8+ Questions→