php的While loops

while循环是简单的块,重复执行直到while循环条件不满足为止。

下面是一个总共执行了10次的循环的示例:

$counter = 0;

while ($counter < 10) {
    $counter += 1;
    echo "Executing - counter is $counter.\n";
}

 

for循环和while循环的主要区别在于for循环用于在数组或对象上迭代,while循环将根据变量条件(例如,直到用户输入正确的输入)执行未知的次数。

流程语句

循环可以使用break和continue流语句进行控制,这在while循环中非常有用。break语句立即在块的中间退出for循环,而continue语句返回while循环的顶部,同时重新检查循环条件是否满足。

Continue语句

让我们使用前面的例子,但这次让我们添加一个检查,看看数字是否是偶数。如果是,我们将跳过它,这样就只打印奇数。

$counter = 0;

while ($counter < 10) {
    $counter += 1;

    if ($counter % 2 == 0) {
        echo "Skipping number $counter because it is even.\n";
        continue;
    }

    echo "Executing - counter is $counter.\n";
}

中断语句

假设我们要添加另一个测试来检查计数器变量是否不大于8。如果是,我们想停止循环。这将导致在本例中不打印数字9。

$counter = 0;

while ($counter < 10) {
    $counter += 1;

    if ($counter > 8) {
        echo "counter is larger than 8, stopping the loop.\n";
        break;
    }

    if ($counter % 2 == 0) {
        echo "Skipping number $counter because it is even.\n";
        continue;
    }

    echo "Executing - counter is $counter.\n";
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *