Understanding PHP's array_merge_recursive() Function
This article explains the PHP array_merge_recursive() function, its syntax, parameters, return values, usage examples with code, and important considerations when merging multidimensional arrays, highlighting how duplicate keys are combined into arrays.
The array_merge_recursive() function is a commonly used PHP function for merging one or more arrays, and unlike array_merge() it can handle multidimensional arrays, merging values of duplicate keys into an array.
Below we detail the usage of array_merge_recursive() .
1. Function Syntax
<code>array_merge_recursive(array1, array2, array3, …)</code>2. Parameter Description
array1 – one of the arrays to be merged (required).
array2, array3, … – additional arrays to merge (optional).
3. Return Value
The function returns a merged array. If duplicate keys are encountered, the values under those keys are combined into an array.
4. Usage Example
The following demonstrates a simple use of array_merge_recursive() :
<code>array1 = array('name' => 'PHP', 'version' => '7.2');
array2 = array('name' => 'MySQL', 'version' => '5.7', 'extension' => array('pdo', 'mysqli'));
$array3 = array('name' => 'HTML', 'version' => '5', 'extension' => array('canvas', 'video'));
$arr = array_merge_recursive($array1, $array2, $array3);
print_r($arr);
</code>Running the above code produces the following output:
<code>Array
(
[name] => Array
(
[0] => PHP
[1] => MySQL
[2] => HTML
)
[version] => Array
(
[0] => 7.2
[1] => 5.7
[2] => 5
)
[extension] => Array
(
[0] => pdo
[1] => mysqli
[2] => canvas
[3] => video
)
)
</code>The result shows that values under duplicate keys like "name" and "version" are merged into arrays.
5. Important Notes
When using array_merge_recursive() , keep in mind:
The order of arrays affects the resulting merged array.
Non‑array values are forced into array type, so the return value is always an array.
If an element being merged is itself an array, the function recurses into that sub‑array and merges its elements.
Strings are not split into individual characters; they remain intact.
Summary
The array_merge_recursive() function is a widely used PHP array‑merging tool suitable for multidimensional arrays; its behavior is influenced by array order, and duplicate keys result in combined array values. Pay attention to the listed considerations to avoid unexpected merge outcomes.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.