Jump to content

Searching a number in an array and increase the counter if found


nirvana

Recommended Posts

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

<?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

)

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.