php循环语句for while do while的用法分享
发布时间:2022-06-24 01:31:05 所属栏目:PHP教程 来源:互联网
导读:php循环语句for while do while的用法. 循环结构 一、for循环 根据循环条件不同,有两种类型的循环 一种:计数循环(一般使用for) 另一种:条件型循环,一般使用 while do-while. for (expr1; expr2; expr3) { statement } 其中的 expr1 为条件的初始值,expr2
php循环语句for while do while的用法. 循环结构 一、for循环 根据循环条件不同,有两种类型的循环 一种:计数循环(一般使用for) 另一种:条件型循环,一般使用 while do-while. for (expr1; expr2; expr3) { statement } 其中的 expr1 为条件的初始值,expr2 为判断的条件,通常都是用逻辑运算符号 (logical operators) 当判断的条件,expr3 为执行 statement 后要执行的部份,用来改变条件,供下次的循环判断,如加一..等等,而 statement 为符合条件的执行部分程序,若程序只有一行,可以省略大括号 {}. 下例是用 for 循环写的 "以后不敢了" 的例子,可以拿来和用 while 循环的比较,代码如下: <?php for ($i=1; $i<=10; $i++) { echo "$i. 以后不敢了<br>n"; } ?> //输出表格 <HEAD> <TITLE>Value of Shares</TITLE> <H3>Table Showing Cost of Shares</H3> <BODY> <TABLE BORDER=1> <?php for ($shares = 1; $shares <= 20; $shares++){ $cost = $shares * 20; echo "<TR><TD>The cost of $shares share/s is $cost #x0024s</TD>","n"; $dividend = $cost * 0.10; echo "<TD>The dividend is $dividend #x0024s</TD></TR> " ,"n"; } ?> </TABLE> </BODY> </HTML> 累加计算,代码如下: <?php $count = 1; while ($count < 5) { echo "$count squared = ".pow($count,2). "<br />"; $count++; } ?> do while 循环,代码如下: <html> <head> <title>The do...while Statement</title> </head> <body> <div> <?php $num = 1; do { print "Execution number: $num<br />n"; $num++; } while ( $num > 200 && $num < 400 ); ?> </div> </body> </html> 。 二、while循环 while(表达式) { 循环体;//反复执行,直到表达式为假 } <?php $num = 1; while ($num <= 10){ print "Number is $num<br />"; $num++; } print 'Done.'; ?> Do While 循环语句与while有一定的区别,它们的区别就是do while不管条件是否为真都会先执行一下,而while必须为真才会执行一次. do { echo "Mmmmm...I love cookies! *munch munch munch*"; } while ($cookies > 1); //输出就是. //Mmmmm...I love cookies! *munch munch munch。 (编辑:锡盟站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐