简体   繁体   English

如何计算不带0的数组值

[英]how to count array values without 0

$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; 得到的计数为5; But I want to count without zeros. 但是我想算不算零。 How to do that? 怎么做? I want to count = 3 我想数= 3

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 (""). 您的数组包含字符串“ $ q1”,“ $ q2”,“ $ q3”等,如果要存储它们的值,甚至不需要使用引号,或者如果要使用双引号(“ )。

You can count them manually like this: 您可以像这样手动计数:

$count = 0;
foreach($array as $el){
    if($el != 0){
        $count++;
    }
}

or use array_filter() built in function. 或使用内置函数array_filter()

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. 如果要不加零计数,可以编写简单的foreach循环。

 $countWithoutZeros=0;
foreach($count as $number){ if($number!=0){$countWithoutZeros++}}

array_filter() is your friend. array_filter()是您的朋友。

$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 您可以在使用@axiac注释时使用过滤器功能进行计数

function nonzero($var){ 
    return ($var > 0); } 


$arr = array_filter($array, "nonzero"); 
echo count($arr); 

Thanks 谢谢

you can use array_filter() and it is built in function so no worry about it. 您可以使用array_filter()并且它是内置函数,因此不必担心。

echo count(array_filter($your_array));

http://php.net/manual/en/function.array-filter.php 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 您也可以使用此代码删除所有0值

$count = array($q1, $q2, $q3, $q4, $q5);
function nonzero($var)
{
 return ($var > 0);
}

$arr = array_filter($count, "nonzero");
echo count($arr);

tyr this :D 这: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() 也了解有关array_filter()的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM