note 76003 added to function.array-count-values
| From: | byron at byronrode dot co dot za | Date: | Tue, 26 Jun 2007 12:19:44 +0000 |
| Subject: | note 76003 added to function.array-count-values | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-127984@lists.php.net to get a copy of this message | ||
I am building a script for a quiz, and could not find any answers to count the number of times a
value was repeated in an array, and came up with the following function.
<?php
// Answers Array
$array = array('a', 'b', 'a', 'a', 'c',
'a', 'd', 'a', 'c', 'd');
// Start Count Function
function count_repeat_values($needle, $haystack){
$x = count($haystack);
for($i = 0; $i < $x; $i++){
if($haystack[$i] == $needle){
$needle_array[] = $haystack[$i];
}
}
$number_of_instances = count($needle_array);
return $number_of_instances;
}
echo count_repeat_values('a', $array);
// will return the value 5
?>
But after writing the function, I happened to stroll upon array_count_values() which I had
completely forgotten about.
I know that i could get the value by doing this:
<?php
$array = array('a', 'b', 'a', 'a', 'c',
'a', 'd', 'a', 'c', 'd');
$answer = array_count_values($array);
echo $answer['a']
?>
Would be interesting to see which version works quicker...
----
Server IP: 69.147.83.197
Probable Submitter: 196.38.131.20
----
Manual Page -- http://www.php.net/manual/en/function.array-count-values.php
Edit -- https://master.php.net/note/edit/76003
Del: integrated -- https://master.php.net/note/delete/76003/integrated
Del: useless -- https://master.php.net/note/delete/76003/useless
Del: bad code -- https://master.php.net/note/delete/76003/bad+code
Del: spam -- https://master.php.net/note/delete/76003/spam
Del: non-english -- https://master.php.net/note/delete/76003/non-english
Del: in docs -- https://master.php.net/note/delete/76003/in+docs
Del: other reasons-- https://master.php.net/note/delete/76003
Reject -- https://master.php.net/note/reject/76003
Search -- https://master.php.net/manage/user-notes.php