The intersection of PHP arrays array_intersect of array_intersect_assoc of array_inter_key of functions

  • 2020-05-05 11:04:12
  • OfStack

The array_intersect_assoc() function binds the keys and values together to compare the sections of the intersection. The array_intersect_key() function compares the keys of two arrays and returns the array of the intersection of the keys.
However, there are some minor problems in the practical application as follows:
Example:
 
<?PHP 
$array = array("red"=>"Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158); 
$array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158); 
$num = array_intersect($array,$array1); 
print_r ($num); 
echo "<br />"; 
$num = array_intersect_assoc($array,$array1); 
print_r($num); 
echo "<br />"; 
$num = array_intersect_key($array,$array1); 
print_r ($num); 
?> 

Result:
 
Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [azzzz1] => art [peak] => 158 ) 
Array ( [Red15] => Red [7] => Level [Width] => Red [peak] => 158 ) 
Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [peak] => 158 ) 

Conclusion:
1. The array_intersect() function only compares array values, and if "Red" and "Red2" are compared, "Red" will be returned; otherwise, "Red2" will not be returned.
2. The array_intersect_assoc() function compares the values of the array with the key values, and there is no array_intersect case, which is suitable for strict comparison.
The array_intersect_key() function compares the intersection of two array keys and returns not just the keys, but the keys and the corresponding array values.

Related articles: