Jump to: navigation, search

Php array merge recursive

From w3cyberlearnings

Contents

PHP function array_merge_recursive

This function merges two or more arrays together. When two or more arrays have the same keys, this function will make the array value to be an other array.

Syntax array_merge_recursive

  • array1: array 1 input
  • array2: array 2 input
array_merge_recursive(array1, array2);

Note

  • array_merge() will override the duplicate key, however the array_merge_recursive will make the duplicate key values to be an array.

Example 1


<?php
$person1 = array('Aviana Olea','Max Liron','Vida Alves');
$person2 = array('Natashya Lorien','Emme Maribel','Maximilian David');

$persons = array_merge_recursive($person1, $person2);

foreach($persons as $p) {
	echo $p.'<br/>';
}
?>

Output

Aviana Olea
Max Liron
Vida Alves
Natashya Lorien
Emme Maribel
Maximilian David

Example 2


<?php

$place1 = array(
	 'Cambodia' => 'Angkor Wat',
	 'China' => 'Great Wall',
	 'Thailand' => 'Bangkor',
	 'USA' => 'Houston,Tx',
	 'Vietnam' => 'DaLat');

$place2 = array(
	 'Cambodia' => 'Phnom Penh',
	 'Mexico' => 'Todos Santos'
);

$places = array_merge_recursive($place1, $place2);

print_r($places);
?>



Output


Array
(
    [Cambodia] => Array
        (
            [0] => Angkor Wat
            [1] => Phnom Penh
        )

    [China] => Great Wall
    [Thailand] => Bangkor
    [USA] => Houston,Tx
    [Vietnam] => DaLat
    [Mexico] => Todos Santos
)


Related Links


Navigation
Web
SQL
MISC
References