If you require the number of differences between array $a and array $b, you should use count($a) - count(array_intersect($a, $b)) instead of count(array_diff($a, $b)) ;
The former is faster than the latter, which is more obvious in large arrays.
1. array_intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect() returns an array, the array Contains all values in array1 that also appear in all other parameter arrays. Note that the key names remain unchanged.
#1 array_intersect() example
Copy code The code is as follows:
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
?>
This makes $result:
Array
(
[a] => green
[0] => red
)
2. The self-implemented array_intersect() function is five times faster than the original PHP function array_intersect()
Copy code The code is as follows:
/**
*
* Custom array_intersect
* If you are looking for the intersection of one-dimensional arrays, this function is 5 times faster than the system array_intersect
*
* @param array $arr1
* @param array $arr2
* @author LIUBOTAO 2010-12-13 11:40:20 AM
*
*/
function my_array_intersect($arr1,$arr2)
{
for( $i=0;$i
{
$temp[]=$arr1[$i];
}
for($i=0; $i{
$temp[]=$arr2[$i];
}
sort($temp);
$get= array();
for($i=0;$i{
if($temp[$i]==$temp[$i+1 ])
$get[]=$temp[$i];
}
return $get;
}
$array1 = array("green", "red", "blue ");
$array2 = array("green", "yellow", "red");
echo "";
print_r(my_array_intersect($array1, $array2));
echo "";
array_diff — Calculate the difference of arrays
array array_diff ( array $array1 , array $ array2 [, array $ ... ] )
array_diff() returns an array that includes all values in array1 that are not in any other parameter array. Note that the key names remain unchanged.
#1 array_diff() example
Copy code The code is as follows:
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow" , "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Multiple in $array1 Values that appear twice are processed in the same way, and the output result is:
Copy the code The code is as follows:
Array
(
[1] => blue
)
Note: Two units are considered identical only if (string) $elem1 === (string) $elem2. That is, when the expressions of the strings are the same.
Note: Note that this function only checks one dimension of the multidimensional array. Of course you can use array_diff($array1[0], $array2[0]); to check deeper dimensions.
http://www.bkjia.com/PHPjc/323709.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323709.htmlTechArticleIf you require the number of differences between array $a and array $b, you should use count($a) - count(array_intersect($a, $b)) instead of count(array_diff($a, $b)); The former is faster than the latter, in large...