PHP array_merge() function
The array_merge()
function in PHP is used to merge one or more arrays into a single array. If the arrays have the same string keys, the later values will overwrite the previous ones. If the arrays have numeric keys, the values from the later arrays will be appended to the result and re-indexed with sequential numeric keys.
Syntax:
Parameters:
- $arrays: One or more arrays to merge. You can pass as many arrays as you want, separated by commas.
Return Value:
- The function returns a new array containing all the elements from the input arrays. If there are duplicate string keys, the last value for that key will be used. For numeric keys, values are re-indexed.
Behavior:
- String Keys: If the input arrays have the same string keys, the values in later arrays will overwrite earlier values.
- Numeric Keys: If the input arrays have numeric keys, the values will be appended to the resulting array and re-indexed starting from 0.
Example 1: Merging Indexed Arrays
When merging arrays with numeric keys, array_merge()
will re-index the result.
Output:
Here, the values from both arrays are merged, and the result is re-indexed starting from 0
.
Example 2: Merging Associative Arrays (String Keys)
When merging arrays with string keys, later values overwrite earlier values.
Output:
In this example, both arrays have the key "name"
. Since the second array ($array2
) comes later, its value ("Bob"
) overwrites the earlier value ("Alice"
).
Example 3: Mixing Numeric and String Keys
array_merge()
treats numeric keys differently from string keys. Numeric keys are re-indexed, while string keys follow the normal overwriting rule.
Output:
In this example, the numeric keys from both arrays are re-indexed sequentially, while the string key "name"
from the second array overwrites the one from the first array.
Example 4: Merging Multiple Arrays
You can merge more than two arrays by passing multiple arrays as arguments.
Output:
Here, three arrays are merged together into one.
Example 5: Handling Non-Array Values
If you pass non-array values to array_merge()
, you will get an error. All arguments passed must be arrays.
Practical Usage:
array_merge()
is useful for:- Combining multiple arrays of data into one.
- Merging configuration settings where later values should overwrite earlier ones.
- Concatenating arrays of data from different sources while keeping order.
Summary:
array_merge($array1, $array2, ...)
merges two or more arrays into one.- Numeric keys are re-indexed, while string keys overwrite earlier values.
- The function returns a new array containing elements from all the input arrays.
- It's a powerful tool for combining arrays but must be used with care when handling keys.