php array_intersect is faster than array_diff. of comes with detailed instructions

  • 2020-05-09 18:20:21
  • OfStack

If you want the number of difference sets between the array $a and the array $b, you should use count($a) -count (array_intersect($a, $b)) instead of count(array_diff($a, $b));

The first is faster than the second, and it's more obvious in a large array.

1. array_intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect() returns an array containing all the values that also appear in all other parameter arrays in array1. Note that the key name remains the same.
Example # 1 array_intersect ()
 
<?php 
$array1 = array("a" => "green", "red", "blue"); 
$array2 = array("b" => "green", "yellow", "red"); 
$result = array_intersect($array1, $array2); 
?> 
 This makes the  $result  Be:  
Array 
( 
[a] => green 
[0] => red 
) 

2. The self-actualized array_intersect() function is 5 times faster than the original php function array_intersect()
 
/** 
* 
*  The custom of array_intersect 
*  If I want to find theta 1 Dimensional array of the intersection of this function than the system array_intersect fast 5 times  
* 
* @param array $arr1 
* @param array $arr2 
* @author LIUBOTAO 2010-12-13 In the morning 11:40:20 
* 
*/ 
function my_array_intersect($arr1,$arr2) 
{ 
for($i=0;$i<sizeof($arr1);$i++) 
{ 
$temp[]=$arr1[$i]; 
} 
for($i=0;$i<sizeof($arr1);$i++) 
{ 
$temp[]=$arr2[$i]; 
} 
sort($temp); 
$get=array(); 
for($i=0;$i<sizeof($temp);$i++) 
{ 
if($temp[$i]==$temp[$i+1]) 
$get[]=$temp[$i]; 
} 
return $get; 
} 
$array1 = array("green", "red", "blue"); 
$array2 = array("green", "yellow", "red"); 
echo "<pre>"; 
print_r(my_array_intersect($array1, $array2)); 
echo "<pre/>"; 

array_diff - calculates the difference set of an array

array array_diff ( array $array1 , array $array2 [, array $ ... ] )
array_diff() returns an array containing all the values in array1 but not in any other parameter array. Note that the key name remains the same.

Example # 1 array_diff ()
 
<?php 
$array1 = array("a" => "green", "red", "blue", "red"); 
$array2 = array("b" => "green", "yellow", "red"); 
$result = array_diff($array1, $array2); 
print_r($result); 
?> 

The value 1 that appears repeatedly in $array1 is processed, and the output result is as follows:
 
Array 
( 
[1] => blue 
) 

Note: two units are considered identical only if (string) $elem1 === (string) $elem2. That is, when the representation of a string is one.

Note: note that this function only checks 1 dimension in a multidimensional array. Of course, you can use array_diff($array1[0], $array2[0]); Check deeper dimensions.

Related articles: