doucheng4660 2016-05-30 13:18
浏览 72

PHP - 如果条件,“更多零”

Often in php i see code lines like

if(count($arr)) // $arr not empty

or

if(!$var) // $var is 0

But for me more informative is style like

if(count($arr) > 0) // or if(!empty($arr))

or

if($var == 0)

Which do same checking. What option is more correct? It's not a problem, but just code-style question. Maybe exists some standard(like PSR-2) for conditions like these.

  • 写回答

1条回答 默认 最新

  • duanhe4267 2016-05-30 13:31
    关注

    The first statement is for counting as it says count(). This can be array values for example.

    <?php
    $array = array("x", "x", "x");
    # Output: 3
    echo count($array);
    ?>
    

    The second statement is for checking if the variable $var is true or not. You can translate this line as if $var is not true, then..

    <?php
    $array = array("x", "x", "x");
    if(!$array) {
        echo "True";
    
    }else{
    
        echo "Does nothing..";
    }
    ?>
    

    The third statement is for checking if the counting for $var is greater than zero.

    <?php
    # Output: "Is not empty!"
    $array = array("x", "x", "x");
    if(count($array) > 0)
        echo "Is not empty!";
    
    }else{
    
        echo "Empty..";
    }
    ?>
    

    And the last one is for checking if $var is equal to zero.

    <?php
    # Output: "Does nothing.."
    $array = array("x", "x", "x");
    if($array == 0) {
        echo "Is not empty!";
    
    }else{
    
        echo "Does nothing..";
    }
    ?>
    

    So basically all these four statements have different meanings. As answer to your question would if(count($arr) > 0) be the best solution to check if the array has more then zero entries.

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'