Home  >  Article  >  Backend Development  >  PHP merge arrays based on key value

PHP merge arrays based on key value

coldplay.xixi
coldplay.xixiforward
2020-07-03 17:52:103177browse

PHP merge arrays based on key value

Let’s now analyze how to merge two arrays and merge elements with the same key value together during the PHP development process.

Example 1

The simplest merge method

$a = [
   1=>'a',
   2=>'b',
   3=>'c'
];
$b = [
   3=>'e',
   4=>'f',
   5=>'c'
];
$c = $a+$b;
print_r($c);

Output:

Array ( [1] => a [2] => b [3] => c [4] => f [5] => c )

Analysis:$ a[3] covers $b[3]. When there are elements with the same key value in the array, the previous array will be followed by the array elements with the same key value

Example 2

Using foreach loop assignment method

$a = [
   1=>'a',
   2=>'b',
   3=>'c'
];
$b = [
   3=>'e',
   4=>'f',
   5=>'a'
];
foreach ($b as $key => $val) {
   $a[$key] = $val;
}
print_r($a);

Output:

Array ( [1] => a [2] => b [3] => e [4] => f [5] => a )

Analysis: A little different from Example 1

Array used for looping $b will overwrite the elements of the array $a, and only overwrite elements with the same key value

Related functions:

array_merge

array_intersect

##array_intersect_ukey

array_intersect_uassoc

array_intersect_key

##array_intersect_assoc

##Related learning recommendations:

PHP programming from entry to proficient

The above is the detailed content of PHP merge arrays based on key value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:liqingbo.cn. If there is any infringement, please contact admin@php.cn delete