Sandeep Kumar Sandeep Kumar - 4 months ago 7
PHP Question

PHP count function

I have to count the numbers which is divisible by 5.

Here is my code,

$num = array(4, 25, 60, 7, 8);

foreach($num as $numbers) {

if(($numbers % 5) == 0) {
echo count($numbers); } }


Output of above program is 11. But output should be 2. Please give me solution. Thanks in advance.

Answer

I think you need to do something more like the following perhaps.

$num = array(4, 25, 60, 7, 8);
$numbers=array();

foreach( $num as $number ) {
    if( $number % 5  == 0 ) $numbers[]=$number;
}
echo count( $numbers );

or alternatively using array_walk and a custom callback function

function mod5($item,$key,$arr){
    if($item %5==0)$arr[]=$item;
}
array_walk( $num,'mod5',&$numbers);
echo count($numbers);