๐น array_merge()
- Definition: Merges one or more arrays into a single array.
- Behavior:
- Numeric keys are reindexed (0,1,2,…).
- String keys are preserved, and if the same key exists in multiple arrays, the later one overwrites the earlier one.
Example:
$a = ["red", "green"];
$b = ["blue", "yellow"];
print_r(array_merge($a, $b));
Output:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => yellow
)
With duplicate string keys:
$a = ["color" => "red", "shape" => "circle"];
$b = ["color" => "blue", "size" => "large"];
print_r(array_merge($a, $b));
Output:
Array
(
[color] => blue // overwritten
[shape] => circle
[size] => large
)
โ
Use array_merge() when you want to combine values of multiple arrays.
๐น array_combine()
- Definition: Creates an array by using one array for keys and another array for values.
- Condition: Both arrays must have the same number of elements, otherwise it throws an error.
Example:
$keys = ["a", "b", "c"];
$values = [1, 2, 3];
print_r(array_combine($keys, $values));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
)
โ ๏ธ If the sizes donโt match:
$keys = ["a", "b"];
$values = [1, 2, 3];
print_r(array_combine($keys, $values));
Error:
Warning: array_combine(): Both parameters should have an equal number of elements
โ
Use array_combine() when you want to map keys to values explicitly.
๐ Key Differences
| Feature | array_merge() | array_combine() |
|---|---|---|
| Purpose | Combines multiple arrays | Creates new array from keys & values |
| Keys handling | Numeric keys reset; String keys preserved | First array = keys, Second array = values |
| Overwriting | Later arrays overwrite same string keys | No overwrite (direct mapping) |
| Size restriction | Any number of arrays | Both arrays must have equal length |
| Example Use Case | Merging config arrays, appending lists | Creating dictionary-like structures |
๐ In short:
- Use
array_merge()when you want to join arrays. - Use
array_combine()when you want to pair keys with values.
