note 82045 added to function.array-count-values
| From: | bluej100 at gmail | Date: | Tue, 25 Mar 2008 21:06:04 +0000 |
| Subject: | note 82045 added to function.array-count-values | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137574@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 208.69.120.35
Probable Submitter: 65.44.120.114
----
Manual Page -- http://www.php.net/manual/en/function.array-count-values.php
Edit -- https://master.php.net/note/edit/82045
Del: integrated -- https://master.php.net/note/delete/82045/integrated
Del: useless -- https://master.php.net/note/delete/82045/useless
Del: bad code -- https://master.php.net/note/delete/82045/bad+code
Del: spam -- https://master.php.net/note/delete/82045/spam
Del: non-english -- https://master.php.net/note/delete/82045/non-english
Del: in docs -- https://master.php.net/note/delete/82045/in+docs
Del: other reasons-- https://master.php.net/note/delete/82045
Reject -- https://master.php.net/note/reject/82045
Search -- https://master.php.net/manage/user-notes.php