How would I count the number of times a specific number occurrs in an array?
I know how to see if it's in the array, I just need to know how many times.
How would I count the number of times a specific number occurrs in an array?
I know how to see if it's in the array, I just need to know how many times.
[man]array_count_values()[/man]
or to more specifically answer your request.
function array_count_this_value($array, $value) {
$values=array_count_values($array);
return $values[$value];
}
You could also use a little recursion and some self counting like this:
<?php
function howMany($needle,$haystack) {
$exists = array_search($needle,$haystack);
//if the desired element exists in the array
if ($exists !== FALSE)
//return 1 and call the function again with the array after the
//first occurance of needle
return 1 + howMany($needle,array_slice($haystack,($exists+1)));
//if the element does not exist return 0;
return 0;
} //end howMany
?>