-4

我有这个代码:

<?php 
$counter = 1;

while ($counter == 5) {
    echo "foo<br />";
    $counter++;
}
?>

我期望的是在单独的行上打印foo 5 次。但我得到的是一个永无止境的循环。PHP while 循环有什么特别之处吗?因为当我在 Python 中做类似的事情时,它工作得很好。

4

3 回答 3

6

你想要while ($counter <= 5)。这意味着“只要$counter小于或等于”就循环通过5

你写它的方式是说“只要$counter等于就循环5”。因为$counter它是1第一次进入你的循环,所以它完全跳过了循环!

于 2012-10-12T05:05:40.677 回答
3

$counter == 5只有当计数器值达到 5 时才会满足,所以它不会像预期的那样打印 5 次。所以试试下面的代码

<?php 
    $counter = 1;

    while ($counter <= 5) {
        echo "foo<br />";
        $counter++;
    }
    ?>

PHP while 循环文档

于 2012-10-12T05:06:10.493 回答
0

您要做的是检查它们是否相等,您应该这样做:-

<?php 
    $counter = 1;

    while ( 5 >= $counter ) {
        echo $counter;
        $counter++;
    }
?>

而且它总是更好,但左侧的值和右侧的变量,它有时会将你从地狱中拯救出来......!

于 2012-10-12T05:30:57.947 回答