📖 PHP array_merge_recursive()
Function — Explained
The array_merge_recursive()
function in PHP is used to merge two or more arrays.
Unlike array_merge()
, which replaces the values of duplicate keys, array_merge_recursive()
combines values with the same keys into an array.
📌 Syntax:
Parameters:
-
$array1, $array2, ...
→ Arrays you want to merge.
Returns:
-
A new merged array. If two arrays have the same string keys, their values will be merged into an array instead of being overwritten.
📖 How It Works:
-
If keys are different: Values are simply added to the result.
-
If keys are the same:
-
If the key is a string → The values are merged into an array.
-
If the key is numeric → The values are appended.
-
📌 Example 1: Simple Merge Without Conflicting Keys
✅ Output:
Explanation:
-
The key
"color"
exists in both arrays, so their values ("red"
and"green"
) are combined into an array. -
Numeric keys are appended sequentially.
📌 Example 2: Nested Array Merge
✅ Output:
Explanation:
-
The
"details"
key exists in both arrays. Since their values are arrays themselves,array_merge_recursive()
merges them.
📌 Example 3: Conflicting Keys (String and Numeric)
✅ Output:
📌 Use Cases:
-
Combining form inputs from multiple sources.
-
Merging configuration arrays without losing values.
-
Combining nested data structures (e.g., merging API responses).
📌 Important Notes:
-
It recursively merges arrays. If values are arrays themselves, it will continue to merge them at deeper levels.
-
Be cautious: It can result in deeply nested structures if arrays have the same keys at multiple levels.
-
If you don’t want this recursive merging behavior, use
array_merge()
instead.
📌 Conclusion:
array_merge_recursive()
is a powerful function when working with complex or nested arrays, where you want to preserve all values, including those under the same keys, by combining them into arrays instead of overwriting.
📌 Official PHP Docs:
👉 https://www.php.net/manual/en/function.array-merge-recursive.php
Comments
Post a Comment