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

PHP merge arrays based on key value

coldplay.xixi
Release: 2023-04-09 06:46:02
forward
3228 people have browsed it

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);
Copy after login

Output:

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

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);
Copy after login

Output:

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

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!

Related labels:
source:liqingbo.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template