Home > Article > Backend Development > How to merge arrays in php without changing key values
The way PHP can merge arrays without changing the key values is to use the [ ] operator to merge arrays, such as [$array=$array1 $array2]. If you do not need to preserve key values, you can use the array_merge function to merge arrays.
The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.
In php we usually use the array_merge() function to merge one or more arrays, as shown below:
For example:
$data1 = ['111' => 'aaa', '222' => 'bbb', '333' => 'ccc']; $data2 = ['444' => 'ddd', '555' => 'eee', '666' => 'fff']; $data = array_merge($data1, $data2); var_dump($data);
Get the result:
array(6) { [0]=> string(3) "aaa" [1]=> string(3) "bbb" [2]=> string(3) "ccc" [3]=> string(3) "ddd" [4]=> string(3) "eee" [5]=> string(3) "fff"}
We can see from the above results that merging arrays using the array_merge() function will reset the key value.
So what if we don’t want to reset the key value and want to keep the original key value? We can use " " to merge two arrays, as shown below:
$data1 = ['111' => 'aaa', '222' => 'bbb', '333' => 'ccc']; $data2 = ['444' => 'ddd', '555' => 'eee', '666' => 'fff']; $data = $data1 + $data2; var_dump($data);
Get the result:
array(6) { [111]=> string(3) "aaa" [222]=> string(3) "bbb" [333]=> string(3) "ccc" [444]=> string(3) "ddd" [555]=> string(3) "eee" [666]=> string(3) "fff"}
Related recommendations: Introduction to Programming
The above is the detailed content of How to merge arrays in php without changing key values. For more information, please follow other related articles on the PHP Chinese website!