Home >Backend Development >PHP Problem >How to compare array values in php
Two comparison methods: 1. Use the array_diff() function to compare the differences in array values. This function can compare the key values of one or more arrays and return different elements. The syntax "array_diff($arr1,$arr2 ...)"; 2. Use the array_diff_assoc() function to compare the differences in array values. This function can compare the key names and key values of one or more arrays and return different elements. The syntax is "array_diff_assoc($arr1,$arr2... )".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
In PHP, you can use the following functions to compare array values The difference
array_diff() function
array_diff_assoc() function
method 1. array_diff() function - compares the key values of the array
array_diff() function only compares the key values of the array
array_diff($arr1,$arr2...)
This function will return a difference array, difference set The elements in the array exist in the compared array $arr1, but do not exist in other parameter arrays $arr2...
Example: Return different elements of the array
<?php header("Content-type:text/html;charset=utf-8"); $arr1=array(1,2,3,4,5,6,7,8,9,10); $arr2=array(2,4,6,8,10); var_dump($arr1); var_dump($arr2); $result=array_diff($arr1,$arr2); echo "两个数组中,不同的元素为:"; var_dump($result); ?>
Method 2, array_diff_assoc() function--Compare the key name and key value of the array
array_diff_assoc() function will compare the key name and key value of the array
array_diff_assoc($arr1,$arr2...)
This function will return a difference set array, and the difference set elements are the same as array_diff() and array_diff_key() It will be obtained from the compared array $arr1.
Example: Return different elements of the array
<?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","c"=>"red","d"=>"yellow"); var_dump($arr1); var_dump($arr2); $result=array_diff_assoc($arr1,$arr2); echo "两个数组中,不同的元素为:"; var_dump($result); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to compare array values in php. For more information, please follow other related articles on the PHP Chinese website!