Home >Backend Development >PHP Problem >How to determine whether array a completely belongs to array b in php
Judgment steps: 1. Use "array_intersect_assoc(array b, array a)" to compare the key names and key values of array a and array b, and return an intersection array containing the same elements; 2. Use "array_diff_assoc( Intersection array, array a)" compares the key names and key values of array a and the intersection array, and returns a difference array containing different elements; 3. Use "$diff==[]" to determine whether the difference array is empty. If If it is empty, array a completely belongs to array b, otherwise it does not belong completely.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php determines array a Whether it completely belongs to array b
In PHP, you can use the array_intersect_assoc() and array_diff_assoc() functions to detect whether array a completely belongs to array b.
Step 1: Use the array_intersect_assoc() function to compare array a and array b and obtain the intersection
array_intersect_assoc() function will compare the key names and keys of array a and array b value, and returns an intersection array containing the same elements
<?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"); var_dump($arr1); var_dump($arr2); echo "交集数组:"; $intersect=array_intersect_assoc($arr1,$arr2); var_dump($intersect); ?>
Step 2:Use the array_diff_assoc() function to compare array a and intersection array, take the difference set
array_diff_assoc() function will compare the key names and key values of array a and the intersection array, and return a difference array containing different elements
echo "差集数组:"; $result=array_diff_assoc($intersect,$arr2); var_dump($result);
Step 3: Use the "==" operator to determine whether the difference array is empty
$diff==[]
If it is empty, then Array a completely belongs to array b
If it is not empty, array a does not completely belong to array b
##Full example code:
<?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"); var_dump($arr1); var_dump($arr2); echo "交集数组:"; $intersect=array_intersect_assoc($arr1,$arr2); var_dump($intersect); echo "差集数组:"; $diff=array_diff_assoc($intersect,$arr2); var_dump($diff); if($diff==[]){ echo '$arr2完全属于$arr1'; }else{ echo '$arr2不完全属于$arr1'; } ?>Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of How to determine whether array a completely belongs to array b in php. For more information, please follow other related articles on the PHP Chinese website!