nirvana Posted May 7, 2007 Share Posted May 7, 2007 Hi All, I would like to find out the count of a particular number in an array and every time that number is found the counter should increase. For example: There's an array containing numbers and I would like to find out how many of them are less than 45. If a number less than 45 is found the counter should increase. I know I should use loop with mathematicl function < and variable counter but I don't know where to start. I searched in PHP manual and couldn't find one. Is there a specific function for this? I am still new to php and your help is much appreciated. thanks in advance, nirvana Link to comment https://forums.phpfreaks.com/topic/50345-searching-a-number-in-an-array-and-increase-the-counter-if-found/ Share on other sites More sharing options...
jitesh Posted May 7, 2007 Share Posted May 7, 2007 <?php $array = array(1, "hello", 1, "world", "hello"); $arr_count = array_count_values($array); $counter =0; foreach($arr_count as $key => $value){ if($value < 45){ $counter = $counter + 1; } } echo $counter; ?> array_count_values (PHP 4, PHP 5) array_count_values -- Counts all the values of an array Description array array_count_values ( array input ) array_count_values() returns an array using the values of the input array as keys and their frequency in input as values. Example 1. array_count_values() example <?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?> The above example will output: Array ( [1] => 2 [hello] => 2 [world] => 1 ) Link to comment https://forums.phpfreaks.com/topic/50345-searching-a-number-in-an-array-and-increase-the-counter-if-found/#findComment-247185 Share on other sites More sharing options...
Barand Posted May 7, 2007 Share Posted May 7, 2007 <?php $ar = range (30,50); $count=0; foreach ($ar as $val) { if ($val < 45) ++$count; } echo $count; // 15 ?> Link to comment https://forums.phpfreaks.com/topic/50345-searching-a-number-in-an-array-and-increase-the-counter-if-found/#findComment-247199 Share on other sites More sharing options...
nirvana Posted May 8, 2007 Author Share Posted May 8, 2007 Thank you, guys. Very helpful and I will try it out. regards, nirvana Link to comment https://forums.phpfreaks.com/topic/50345-searching-a-number-in-an-array-and-increase-the-counter-if-found/#findComment-247762 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.