📖 PHP array_merge_recursive()
Function — Explained
The array_merge_recursive()
function in PHP is used to merge two or more arrays recursively. It helps you combine values under the same keys without overwriting any data.
Unlike array_merge()
, which replaces duplicate keys, this function keeps both values by converting them into arrays.
🔑 Keyword Focus: php array_merge_recursive preserve numeric keys
If you're trying to preserve numeric keys while merging arrays in PHP, it's important to know that array_merge_recursive()
will reindex numeric keys by default. Let’s see what that means.
📌 Syntax
array_merge_recursive(array $array1, array $array2, ...): array
Parameters:
$array1, $array2, ...
– Arrays you want to merge
Returns:
- New merged array.
- String keys: merged into arrays.
- Numeric keys: reindexed and appended.
📌 Example 1: Simple Merge Without Conflicting Keys
Output:
Explanation: "color" exists in both arrays, so its values are combined. Numeric keys are reindexed sequentially.
📌 Example 2: Nested Array Merge
Output:
Explanation: Since the "details" key contains arrays in both, they are merged recursively into one array.
📌 Example 3: Conflicting Keys (String and Numeric)
Output:
📦 Use Cases
- Merging form data from different sources
- Combining multiple config files
- Joining nested arrays from API responses
⚠️ Important Notes
- Recursively merges arrays at all levels
- Can cause deep nesting if keys repeat
- Numeric keys are not preserved — use
$array1 + $array2
if needed
📌 Conclusion
array_merge_recursive()
is great for merging arrays deeply without losing values. But if you're concerned about numeric key preservation, this function may not be ideal.
For preserving numeric keys, use the +
operator or build a custom function that suits your logic.
📘 Official PHP Docs
💡 Keyword Recap:
- php array_merge_recursive preserve numeric keys
- php merge arrays without overwriting
- php array merge nested
Comments
Post a Comment