$q1=15;
$q2=12;
$q3=23;
$q4=0;
$q5=0;
$count = array ($q1, $q2, $q3, $q4, $q5);
echo count($count);
This get the count as 5; But I want to count without zeros. How to do that? I want to count = 3
you can use array_filter() and it is built in function so no worry about it.
echo count(array_filter($your_array));
http://php.net/manual/en/function.array-filter.php
<?php
$q1=15;
$q2=12;
$q3=23;
$q4=0;
$q5=0;
$count = array ($q1, $q2, $q3, $q4, $q5);
echo count(array_filter($count));
if you want to check your final array value then use this code also
$count = array($q1, $q2, $q3, $q4, $q5);
$final_arr = array_filter($count);
echo "<pre>";
print_r($final_arr);
you can use this code also which remove all 0 value
$count = array($q1, $q2, $q3, $q4, $q5);
function nonzero($var)
{
return ($var > 0);
}
$arr = array_filter($count, "nonzero");
echo count($arr);
Your array contains strings "$q1", "$q2", "$q3" and so on, if you want to store their values you dont even need to use quotes, or if you want to you can use double quotes ("").
You can count them manually like this:
$count = 0;
foreach($array as $el){
if($el != 0){
$count++;
}
}
or use array_filter()
built in function.
This is wrong way to declare array becouse you are passing strings to array. You should add variables without ''. If you want to count without zero you could write simple foreach loop.
$countWithoutZeros=0;
foreach($count as $number){ if($number!=0){$countWithoutZeros++}}
array_filter()
is your friend.
$q1=15;
$q2=12;
$q3=23;
$q4=0;
$q5=0;
$a = array ($q1, $q2, $q3, $q4, $q5);
# Method 1
$b = array_filter($a, function($v){return $v !== 0;});
var_dump($b);
echo "<p>Count: ".count($b)."</p>";
# Method 2
$b = array_filter($a);
var_dump($b);
echo "<p>Count: ".count($b)."</p>";
Try this:
$q1=15;
$q2=12;
$q3=23;
$q4=0;
$q5=0;
$count = array ($q1, $q2, $q3, $q4, $q5);
$count = array_filter($count);
echo count($count);
You can count using the filter function as @axiac is commented
function nonzero($var){
return ($var > 0); }
$arr = array_filter($array, "nonzero");
echo count($arr);
Thanks
tyr this :D
$c=0;
$count = array ('$q1','$q2','$q3','$q4','$q5');
for(i=0;i<count($count);i++){
if(!$count[$i]==0){
$c++}
else{ continue; }
}
echo $c;
also read about array_filter()