How To Merge Two Array Or Multiple Array In PHP
Encrypting your link and protect the link from viruses, malware, thief, etc! Made your link safe to visit.
This PHP tutorial help to understand array_merge() php function. I will merge two or multiple array and stored into another array.This is very simple and easy in PHP language using array_merge() function.The key will be overridden, if the two elements have the same string keys then the latter value will be overridden.
The PHP provides array_merge() built-in function to merge single or many arrays.We just pass source arrays and destination array variable name.This function is used to merge the elements or values of two or more arrays into a single array.The array_merge() method appended one array elements at the end of the previous array.
The Syntax Of Array_merge() Method
The array_merge() function takes list of arrays separated by commas as a parameter.This method return a new array with merged values of arrays passed in parameter.
array array_merge($array1, $array2, ......, $arrayn)
PHP Array Merge With Same Key
As I discussed at the beginning of the tutorial, The array merge method will overridden two element same string keys by latter value.
The source code –
"banana", 2, "phpflow", 3);
$array2 = array("fruit" => "apple", "city" => "paris", 4, "c");
// Merging arrays together
$result = array_merge($array1, $array2);
print_r($result);
?>
Result
Array
(
[0] => 1
[fruit] => apple
[1] => 2
[2] => phpflow
[3] => 3
[city] => paris
[4] => 4
[5] => c
)Array Merge With Integer Keys
We can also passed arrays with integer key as a parameter into this method.The array_merge() method will renumbered key and append with previous array, The key will start from 0 and increment for next elements by 1.
The source code –
"apple", 2 => "banana", 4 => "Lychee");
// Merging arrays together
$result = array_merge($array1);
print_r($result);
The Result Is
Array
(
[0] => apple
[1] => banana
[2] => Lychee
)
Merge Two Array In PHP With Integer Keys
This example code help to merge two multiple array using array_merge method.
The source code –
"apple", 2 => "banana", 3 => "Lychee", 5 => "avocado");
$array2 = array(0 => "red", 2 => "green", 4 => "yellow", 5 => "black");
// Merging arrays together
$result = array_merge($array1, $array2);
print_r($result);
The Result Is
Array
(
[0] => apple
[1] => banana
[2] => Lychee
[3] => avocado
[4] => red
[5] => green
[6] => yellow
[7] => black
)
0 Response to "How To Merge Two Array Or Multiple Array In PHP"
Post a Comment