技术开发 频道

PHP开发经典教程(Part 3):循环

 

平方运算

    在PHP中学习的第一个及最简单的循环是所谓的while()循环,其看起来像如下所示这样:

while (condition is true) {
    do this!
}

 

 

 

 

    在此实例中,只要指定的条件所求值为真(记住在第二章中所学的),那么在大括号内的PHP语句将继续执行。条件一旦变成假,循环将断开且其后的语句将得到执行。 

    下面是一解释while()循环的快捷例子。
<html> <head></head> <body> <form action="squares.php" method="POST"> Print all the squares between 1 and <input type="text" name="limit" size="4" maxlength="4"> <input type="submit" name="submit" value="Go"> </form> </body> </html>
    这是要求用户输入一数字的简单表单。当提交表单时,所调用的PHP脚本应取得该数字且打印在1与所输入的值之间的所有数字的平方。使用while()循环,这个功能实现起来极其简单:
<html> <head></head> <body> <?php // set variables from form input $upperLimit = $_POST['limit']; $lowerLimit = 1; // keep printing squares until lower limit = upper limit while ($lowerLimit <= $upperLimit) { echo ($lowerLimit * $lowerLimit).'&nbsp;'; $lowerLimit++; } // print end marker echo 'END'; ?> </body> </html>
    该脚本使用while()循环以自1向前计数直到$lowerLimit的值与$upperLimit相等。
0
相关文章