Voting

: zero minus zero?
(Example: nine)

The Note You're Voting On

yuval at visualdomains dot com
9 years ago
Using isset to achieve this, is many times faster:

<?php

$m
= range(1,1000000);
$s = [2,4,6,8,10];

// Use array_intersect to return all $m values that are also in $s
$tstart = microtime(true);
print_r (array_intersect($m,$s));
$tend = microtime(true);
$time = $tend - $tstart;
echo
"Took $time";

// Use array_flip and isset to return all $m values that are also in $s
$tstart = microtime(true);
$f = array_flip($s);
/* $f now looks like this:
(
[2] => 0
[4] => 1
[6] => 2
[8] => 3
[10] => 4
)
*/
// $u will hold the intersected values
$u = [];
foreach (
$m as $v) {
if (isset(
$f[$v])) $u[] = $v;
}
print_r ($u);
$tend = microtime(true);
$time = $tend - $tstart;
echo
"Took $time";
?>

Results:

Array
(
[1] => 2
[3] => 4
[5] => 6
[7] => 8
[9] => 10
)
Took 4.7170009613037
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Took 0.056024074554443

array_intersect: 4.717
array_flip+isset: 0.056

<< Back to user notes page

To Top