PHP compares the key values ​​​​of two arrays and returns the intersection function array_intersect()

黄舟
Release: 2023-03-17 07:44:01
Original
2148 people have browsed it

Example

Compare the key values ​​of two arrays and return the intersection:

"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_intersect($a1,$a2);
print_r($result);
?>
Copy after login

Definition and usage

array_intersect() function is used Compares the key values ​​of two (or more) arrays and returns the intersection.

This function compares the key values ​​​​of two (or more) arrays and returns an intersection array that includes everything in the compared array (array1) and any other parameter arrays. (array2 or array3, etc.).

Syntax

array_intersect(array1,array2,array3...);
Copy after login
ParametersDescription
array1 Required. The first array to compare with other arrays.
array2Required. The array to compare to the first array.
array3,...Optional. Additional array to compare with the first array.

Technical details

Return value: Returns an intersection array, which contains All keys in the compared array (array1) that are also in any other parameter arrays (array2 or array3, etc.).
PHP version: 4.0.1+

更多实例

实例 1

比较三个数组的键值,并返回交集:

"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");

$result=array_intersect($a1,$a2,$a3);
print_r($result);
?>
Copy after login

使用array_intersect()函数时要注意:只有在两个元素相等且具有相同的数据类型时,array_intersect()函数才会认为它们是相同的,否则不能进行交集计算。array_intersect()函数返回一个保留了键的数组,只由第一个数组中出现的且在其它数组中都出现的值组成。

若要求关联数组的交集,请使用array_intersect_assoc()函数,给你个简单的例子:

"Apple","yellow"=>"Banana","orange"=>"Orange");
$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
$intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3);
print_r($intersection);
// 输出:
// Array ( [red] => Apple )
?>
Copy after login

array_intersect_assoc()函数语法格式如下:

array array_intersect_assoc(array array1,array array2[,arrayN…])
Copy after login


The above is the detailed content of PHP compares the key values ​​​​of two arrays and returns the intersection function array_intersect(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!