note 82045 deleted from function.array-count-values by felipe

From: Date: Tue, 25 Mar 2008 21:51:23 +0000
Subject: note 82045 deleted from function.array-count-values by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137577@lists.php.net to get a copy of this message
Note Submitter: bluej100@gmail ---- byron at byronrode dot co dot za, just using count(array_keys($haystack, $needle)) is about three times faster. Alternatively, if you're concerned about memory, you can just increment $number_of_instances instead of keeping an array of equal values. <?php $haystack = Array(); for ($i = 0; $i < 1000000; $i++) { $haystack[] = rand(1, 2000); } $needle = rand(1, 2000); // count(array_keys()) $start = microtime(true); echo count(array_keys($haystack, $needle))."\n"; echo (microtime(true) - $start)."\n"; // 0.08 // $needle_array[] $start = microtime(true); $x = count($haystack); for($i = 0; $i < $x; $i++){ if($haystack[$i] == $needle){ $needle_array[] = $haystack[$i]; } } $number_of_instances = count($needle_array); echo $number_of_instances."\n"; echo (microtime(true) - $start)."\n"; // 0.25 // $number_of_instances++; $start = microtime(true); $x = count($haystack); $number_of_instances = 0; for($i = 0; $i < $x; $i++){ if($haystack[$i] == $needle){ $number_of_instances++; } } echo $number_of_instances."\n"; echo (microtime(true) - $start)."\n"; // 0.25 ?>

« previous php.notes (#137577) next »