Home  >  Article  >  Backend Development  >  Compare php methods to get the same and different elements of two arrays

Compare php methods to get the same and different elements of two arrays

小云云
小云云Original
2018-03-22 15:00:036054browse

This article mainly shares and compares the methods of obtaining the same and different elements of two arrays in PHP. I hope it can help everyone.

1. Get the same elements of the array

array_intersect()This function compares the key values ​​​​of two (or more) arrays and returns the intersection array , this array includes all in the compared array (array1),

is also a key value in any other parameter array (array2 or array3, etc.) .

##

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

$result=array_intersect($a1,$a2);
print_r($result);

//
Array ( [a] => red [b] => green [c] => blue )

array_intersect_assoc() The function is used to compare the key names and key values ​​of two (or more) arrays, and return the intersection. Different from the array_intersect() function, in addition to comparing key values, this function

also compares key names. The keys of the elements in the returned array remain unchanged.

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

$result=array_intersect_assoc($a1,$a2);
print_r($result);
?>
//
Array ( [a] => red [b] => green [c] => blue )

2、获取数组中不同元素

array_diff() 函数返回两个数组的差集数组。该数组包括了所有在被比较的数组中,但是不在任何其他参数数组中的键值。

在返回的数组中,键名保持不变。


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

$result=array_diff($a1,$a2);
print_r($result);
?>
//
Array ( [d] => yellow )

array_diff_assoc() 函数用于比较两个(或更多个)数组的键名和键值 ,并返回差集。

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

$result=array_diff_assoc($a1,$a2);
print_r($result);
//
Array ( [d] => yellow )

相关推荐:

详解PHP实现查找两个数组中不同元素的方法

php比较两个数组的键值并返回差集的函数array_udiff()

php比较两个数组的键值并返回交集的函数array_intersect()

The above is the detailed content of Compare php methods to get the same and different elements of two arrays. 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