Home >Backend Development >PHP Problem >How to compare arrays in php and obtain different elements
Method: 1. Use array_diff() to compare based on the array key value, the syntax is "array_diff(array 1, array 2)"; 2. Use array_diff_assoc() to compare based on the array "key/value pair", Syntax "array_diff_assoc(array1,array2)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Use array_diff() Function - Compare the key values of the array
array_diff($arr1,$arr2...)
The function only compares the key values of the array and will return a difference array. The elements in the set array exist in the compared array $arr1
, but do not exist in other parameter arrays $arr2...
.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow"); var_dump($arr1); var_dump($arr2); $result=array_diff($arr1,$arr2); echo "两个数组中,不同的元素为:"; var_dump($result); ?>
Output result:
Method 2: Use array_diff_assoc() function --Compare the key names and key values of the array
array_diff_assoc($arr1,$arr2...)
The function will compare the key names and key values of the array and return the same A difference array, the difference elements will be obtained from the compared array $arr1
just like array_diff().
<?php header("Content-type:text/html;charset=utf-8"); $arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $arr2=array("a"=>"orange","b"=>"green","e"=>"red","r"=>"yellow"); var_dump($arr1); var_dump($arr2); $result=array_diff_assoc($arr1,$arr2); echo "两个数组中,不同的元素为:"; var_dump($result); ?>
Output result:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to compare arrays in php and obtain different elements. For more information, please follow other related articles on the PHP Chinese website!