PHP array_merge_recursive function
The function PHP array_merge_recursive Merge one or more arrays recursively
Description / Descripciónarray_merge_recursive(array ...$arrays): arraySintaxis / Sintax
$rm_array = array_merge_recursive($array1,$array2)
Cases
The array_merge_recursive
function is similar to array_merge
; their cases are practically the same. Let’s review this before continuing:
Associative Arrays
If the compared arrays have the same key, they will be merged, creating an array that contains the values. For example:
Let’s suppose the key is “name,” and one array has “name” => “Pepe” while the other has “name” => “Marta.” In the new array, it will look like this:
"name" => Array( [0]=>"Pepe", [1]=>"Marta" )
This is done recursively; therefore, if any of the values is an array, the function will also perform a merge with the corresponding entry from another array. We will see this in the examples.
Indexed Arrays and Numerics Arrays
If the arrays have the same numeric key, it will not be overwritten; instead, it will be a new key added to the end of the new array.
Parameters
...$arrays
-These are the arrays to which we will apply array_merge_recursive
.
Returns
array -This array will be the result of combining the arrays with each other. If there are no arguments, the array will be empty [].
Examples
In the first example, we will see the case where we have 2 associative arrays, and within these, we have arrays.
Ejemplo de array_merge_recursive con arrays internos$array1 = array( "person" => array( "name" => "John", "age" => 30, "address" => array( "city" => "Example City", "country" => "Example Country" ) ), "hobbies" => array("reading", "traveling", "coding") ); $array2 = array( "person" => array( "name" => "Jane", "address" => array( "city" => "Another City" ) ), "hobbies" => array("swimming", "photography") ); $result = array_merge_recursive($array1, $array2); print_r($result);
Array ( [person] => Array ( [name] => Array ( [0] => John [1] => Jane ) [age] => 30 [address] => Array ( [city] => Array ( [0] => Example City [1] => Another City ) [country] => Example Country ) ) [hobbies] => Array ( [0] => reading [1] => traveling [2] => coding [3] => swimming [4] => photography ) )
As a second example, we will consider cases involving an indexed or numeric array.
Ejemplo de array_merge_recursive con 2 array indexados$array1 = array("apple", "banana", "orange"); $array2 = array("grape", "kiwi", "melon"); $result = array_merge_recursive($array1, $array2); print_r($result);
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => kiwi [5] => melon )