Voting

: min(five, zero)?
(Example: nine)

The Note You're Voting On

Mike Block
12 years ago
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't as elaborate, but handles most cases and is much faster:

<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
$a_assoc = $a != array_values($a);
$b_assoc = $b != array_values($b);
$ak = $a_assoc ? array_keys($a) : $a;
$bk = $b_assoc ? array_keys($b) : $b;
$out = array();
for (
$i=0;$i<sizeof($ak);$i++) {
if (
in_array($ak[$i],$bk)) {
if (
$a_assoc) {
$out[$ak[$i]] = $a[$ak[$i]];
} else {
$out[] = $ak[$i];
}
}
}
return
$out;
}

?>

You can try this out with this:

<?php
// create a large array (simple)
$first = array();
for (
$i=500;$i<500000;$i++) {
$first[] = $i;
}
// create a smaller array (associative)
$second = array();
for (
$i=499990;$i<500000;$i++) {
$second[$i] = rand();
}
echo
microtime(true)."\n";
// built-in function
print_r(array_intersect($first,$second));
echo
microtime(true)."\n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo
microtime(true)."\n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo
microtime(true)."\n";

?>

<< Back to user notes page

To Top