note 117289 added to function.array-intersect

From: Date: Sun, 17 May 2015 13:17:31 +0000
Subject: note 117289 added to function.array-intersect
Groups: php.notes 
Request: Send a blank email to php-notes+get-202576@lists.php.net to get a copy of this message
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 ---- Server IP: 72.52.91.14 Probable Submitter: 81.218.139.3 ---- Manual Page -- http://php.net/manual/en/function.array-intersect.php Edit -- https://master.php.net/note/edit/117289 Del: integrated -- https://master.php.net/note/delete/117289/integrated Del: useless -- https://master.php.net/note/delete/117289/useless Del: bad code -- https://master.php.net/note/delete/117289/bad+code Del: spam -- https://master.php.net/note/delete/117289/spam Del: non-english -- https://master.php.net/note/delete/117289/non-english Del: in docs -- https://master.php.net/note/delete/117289/in+docs Del: other reasons-- https://master.php.net/note/delete/117289 Reject -- https://master.php.net/note/reject/117289 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#202576) next »