The array_merge()
function in PHP is used to merge one or more arrays into a single array. It combines the elements of the arrays, appending values from the later arrays to the earlier ones. If the arrays have the same string keys, the later value overrides the earlier one. If the arrays contain numeric keys, the values are reindexed.
🔹 Syntax
array_merge(array $array1, array $array2, ...): array
🔸 Examples
1. Merging Indexed Arrays
$array1 = ["apple", "banana"];
$array2 = ["cherry", "date"];
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
[3] => date
)
2. Merging Associative Arrays
$array1 = ["a" => "red", "b" => "green"];
$array2 = ["c" => "blue", "b" => "yellow"];
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[a] => red
[b] => yellow // 'b' is overwritten
[c] => blue
)
3. Merging Mixed Arrays
$array1 = ["a" => "red", "green"];
$array2 = ["blue", "a" => "yellow"];
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[a] => yellow
[0] => green
[1] => blue
)
Explanation:
"a"
is overwritten by the second array.
- Numeric keys (
0
, 1
) are reindexed.
⚠️ Notes
- Use
+
(array union operator) if you want to keep values from the first array when keys are the same.
$array1 + $array2;