doutian4046 2014-08-06 01:42
浏览 20
已采纳

while($ variable)在PHP中意味着什么?

I am new to PHP and am currently constructing a do/while loop from a tutorial. I would understand if the whole condition was ($variable == true) or ($variable == false), however in the tutorial the while condition is simply while($variable). Could anyone explain this to me?

Here is the tutorial code.

<?php
    $loopCond = false;
    do {
        echo "<p>The loop ran even though the loop condition is false.</p>";
    } while ($loopCond);


    echo "<p>Now the loop is done running.</p>";
?>
  • 写回答

7条回答 默认 最新

  • dongyaobo9081 2014-08-06 01:50
    关注

    All such conditional statements, including while and if, are evaluating the given expression against true. If the expression results in true, the statement executes the action. If it results in false, it won't.

    $var == true is an expression which compares $var to true. The result of this expression is either true or false. The important point to understand here is expressions. Expressions are things which return values. Try var_dump($var == true) or var_dump(4 > 6). It shows you that the expressions return a boolean value. Here:

    if ($var == true)
    

    first $var is compared to true, which yields either the value true or false, which is then evaluated by if whether it's true or false, which then prompts if to execute the following statement or not.

    In other words: it's redundant.

    if ($var)
    

    This simply causes if to evaluate whether $var is true or false and then execute the following statement. The == true is essentially already "built in".

    The following statements are all essentially equivalent:

    if ($var)
    if ($var == true)
    if (($var == true) == true)
    if ((($var == true)) == true) == true)
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部