Home >Backend Development >PHP Problem >How to merge arrays in php without changing key values

How to merge arrays in php without changing key values

王林
王林Original
2021-05-13 14:38:022089browse

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.

How to merge arrays in php without changing key values

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn