Comparison steps: 1. Use the "array_diff_assoc($arr1,$arr2)" statement to compare the key names and key values of the two arrays and return a difference array; 2. Use "difference array ==[] " statement determines whether the difference array is an empty array. If it is an empty array, it means that the two arrays being compared are equal, otherwise they are not equal.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In php, you can use the array Difference set to determine whether two arrays are equal.
If the difference between the two arrays is empty, then there are no different elements in the two arrays, that is, the two arrays are equal
If the difference set of the two arrays is not empty, then there are different elements in the two arrays, that is, the two arrays are not equal.
So what about the difference set of the arrays? Get Ni? You can use the array_diff_assoc() function.
array_diff_assoc() is used to compare the key names and key values of two (or more) arrays and return the difference array.
Only two arrays are equal if their array key names and key values are equal.
Implementation steps:
1. Use array_diff_assoc() to obtain the array difference set
<?php header("content-type:text/html;charset=utf-8"); $arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $arr2=array("a"=>"red","b"=>"green","c"=>"blue"); $arr3=array("a"=>"red","b"=>"green","c"=>"blue"); $diff1=array_diff_assoc($arr1,$arr2); var_dump($diff1); $diff2=array_diff_assoc($arr2,$arr3); var_dump($diff2); ?>
It can be seen from the output that there is a difference set between $arr1 and $arr2, but there is no difference set between $arr2 and $arr3
2. Determine whether the difference set array is an empty array
if($diff1==[]){ echo "两数组相等<br>"; } else{ echo "两数组不相等<br>"; }
Because the difference arrays of $arr1 and $arr2 are not empty arrays, so they are not equal
if($diff2==[]){ echo "两数组相等<br>"; } else{ echo "两数组不相等<br>"; }
Because $arr2 and $arr3 are empty arrays, Therefore equal.
Extension: Encapsulate the code:
<?php header("content-type:text/html;charset=utf-8"); function f($arr1,$arr2){ $diff1=array_diff_assoc($arr1,$arr2); if($diff1==[]){ echo "两数组相等<br>"; } else{ echo "两数组不相等<br>"; } } $arr1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $arr2=array("a"=>"red","b"=>"green","c"=>"blue"); $arr3=array("a"=>"red","b"=>"green","c"=>"blue"); f($arr1,$arr2); f($arr2,$arr3); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to compare two arrays for equality in php. For more information, please follow other related articles on the PHP Chinese website!