Home >Backend Development >PHP Problem >What are the methods to merge arrays in php
Merge method: 1. Use the "array 1 array 2" statement; 2. Use the "array_merge (array 1, array 2)" statement; 3. Use the "array_merge_recursive (array 1, array 2)" statement; 4. Use the "array_combine(array1, array2)" statement.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Directly merge the values of the two arrays into one array;
<?php $a = [1,2,3,'a'=>'a']; $b = ['a'=>'b',4,5,'b'=>'c',6,7,'a']; $c = $a + $b; var_dump($a); var_dump($b); var_dump($c); ?>
Output result:
Use " " to merge the arrays, if When the keys are the same, the previous array value will overwrite the following array value.
to directly merge two arrays. If the keys of the two arrays are the same, the value of the latter array overwrites the value of the previous array
<?php $a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'c','b'=>'d','c'=>'e']; $c = array_merge($a,$b); var_dump($a); var_dump($b); var_dump($c); ?>
Output result:
#It can be seen that when the two array keys are the same, the value of the latter array overwrites the value of the previous array. However, for numeric indexes or numeric string indexes, they will be reset in order (the first numeric index element of the first array is filled in sequence starting from 0)
Merge arrays, when encountering the same key, merge the values in the key into a sub-array
<?php $a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'a','b'=>'d','c'=>'e']; $c = array_merge_recursive($a,$b); var_dump($a); var_dump($b); var_dump($c); ?>
Output result:
<?php $a=array("a","b","c","d"); $b=array("red","green","blue","yellow"); $c = array_combine($a,$b); var_dump($a); var_dump($b); var_dump($c); ?>Output result:
PHP Video Tutorial"
The above is the detailed content of What are the methods to merge arrays in php. For more information, please follow other related articles on the PHP Chinese website!