silver
silver

Reputation: 49

calculating size of numbers in array in php

<?php
$broj=array(20,21,10,50,21,9,8,19);
$a=0;
foreach($broj <= 20){
$a + 1;
return $a;}
?>

Php says that something is wrong with foreach loop! how can i see how many numbers in var"$broj" are smaller than 20??

Upvotes: 0

Views: 57

Answers (3)

Hanky Panky
Hanky Panky

Reputation: 46900

echo count(array_filter($broj, function($v) {return $v<20;}));

Nothing more :)

Fiddle

Result for your input: 4

Oh yeah some explanation!

array_filter takes your array and applies a callback to it and returns the resulting array. In that callback method i'm telling it to return only the values that are smaller than 20.

Upvotes: 1

Fr4ncx
Fr4ncx

Reputation: 356

<?php
$broj=array(20,21,10,50,21,9,8,19);
$a=0;
foreach($broj as $value){
  if($value<=20){
   $a++;
  }
}
echo $a;
?>

Upvotes: 0

P. Gearman
P. Gearman

Reputation: 1166

The way a foreach loop works, you have to do the following

$testArray = array(1,1,2,3,5,8,13);

foreach($testArray as $number)
{
    .... whatever your loop code is ....
}

.... after foreach code ....    

Upvotes: 0

Related Questions