Home > Article > Backend Development > How to merge two or more arrays in PHP
Merging two or more arrays in PHP includes: operator " ", array_merge() function, array_merge_recursive() function. Let's introduce in detail how to merge arrays. I hope it will be helpful to everyone. [Recommended related video tutorials: PHP Tutorial]
Use the operator " "
Array of PHP The operator " " can be used to combine two (or more arrays).
<?php header("content-type:text/html;charset=utf-8"); $x = array("red", "green","orange"); $y = array("red","blue","yellow","cyan"); $z = $x + $y; // $x 与 $y 的联合 var_dump($z); ?>
Output:
It can be seen that only the 4th value in the second array is included in the result because the first Three elements have the same keys as the first array element. Next, let's look at the role of the array union operator " " when the array index does not match:
<?php header("content-type:text/html;charset=utf-8"); $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); $z = $x + $y; // $x 与 $y 的联合 var_dump($z); ?>
Output:
It can be seen that: array operations The character " " does not reorder the index in the results.
Using the array_merge() function
The array_merge() function can be used to merge two or more arrays into one array, for example:
<?php header("content-type:text/html;charset=utf-8"); $x = array("0" => "red", "1" => "green","2" => "yellow"); $y = array("3" => "blue", "2" => "yellow","1" => " orange"); $z = array_merge($x, $y); // $x 与 $y 的联合 var_dump($z); ?>
Output:
As can be seen, the numeric index passed to the array key by the array_merge() function is renumbered starting from zero in the returned array.
Use the array_merge_recursive() function
The array_merge_recursive() function can merge one or more arrays into one array.
<?php header("content-type:text/html;charset=utf-8"); $x = array("0" => "red", "1" => "green","2" => "yellow"); $y = array("3" => "blue", "2" => "yellow","1" => " orange"); $z = array_merge_recursive($x, $y); // $x 与 $y 的联合 var_dump($z); ?>
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to merge two or more arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!