【问题标题】:How to count input that have value?如何计算有价值的输入?
【发布时间】:2014-02-22 09:03:51
【问题描述】:

在我的代码中,当我们单击确定按钮时。它会回显 3

我想申请只计算只有值的输入

怎么办?

<?php
    if(isset($_POST["submit"]))
    {
     echo count($_POST["to_more"]);
    }
?>
<form name="f1" method="post">
<input type="text" name="to_more[]">
<input type="text" name="to_more[]">
<input type="text" name="to_more[]">
<input type="submit" name="submit" value="OK">
</form>

【问题讨论】:

  • 循环它而不是只有你会得到计数。
  • 循环 $_POST['to_more'] ,如果它包含值,则计算它们

标签: php forms input count submit


【解决方案1】:

array_filter 应该有帮助

<?php
    $ar = isset($_POST["to_more"]) ? $_POST["to_more"] : array();
    $ar = array_filter($ar, function($el){ return !empty($el);});
    echo count($ar);
?>

应该比 foreach 更快,顺便说一句。

UPD:哦,看来,NLSaini 发布了精确的解决方案,检查一下。

【讨论】:

    【解决方案2】:

    试试这个

    <?php
        if(isset($_POST["submit"]))
        {
         echo count(array_filter($_POST["to_more"]));
        }
    ?>
    

    【讨论】:

      【解决方案3】:

      怎么样

      if(isset($_POST["submit"])){
           $count = 0 ;
           foreach($_POST["to_more"] as $data){
                      if($data != '') $count++;
      
           }
               if($count > 0)
                      echo $count;
          }
      

      【讨论】:

        猜你喜欢
        • 2015-10-29
        • 1970-01-01
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 2022-12-31
        相关资源
        最近更新 更多