Answer the question
In order to leave comments, you need to log in
What is the alternative to native array_intersect in PHP?
Probably many people know about it.
We are writing a simple function to find the intersection of two arrays without keys.
Something like that
function array_intersect2($a, $b) {
$al = count($a);
$bl = count($b);
sort($a);
sort($b);
$max = ($a[$al - 1] > $b[$bl - 1]) ?
$a[$al - 1] :
$b[$bl - 1];
$min = ($a[0] < $b[0]) ?
$a[0] :
$b[0];
$c = array();
foreach($a as $i) {
if($i > $min && $i < $max) {
$c[] = $i;
}
}
foreach($b as $i) {
if($i > $min && $i < $max) {
$c[] = $i;
}
}
return $c;
}
$a = array();
$b = array();
for($i = 0; $i < 50000; $i++) {
$a[] = mt_rand(0, 100000);
$b[] = mt_rand(0, 100000);
}
Answer the question
In order to leave comments, you need to log in
You have some kind of limitation in the function that gives the payoff. This is normal.
For example, I use my self-written json_encode function with a restriction on the dimension of arrays. Due to this (the extra check is_array is eliminated), my self-written function is about 3 times faster than the native one.
You have numeric arrays. Try with other types of values, such as long strings.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question