php专区

 首页 > php专区 > 正则表达式 > php循环语句for while do while的用法

php循环语句for while do while的用法

分享到:
【字体:
导读:
          php循环语句for while do while的用法. 循环结构 一、while循环 while (表达式) { 循环体; //反复执行,直到表达式为假 } ?php $num =1; while ( $num =10){ print Numberis$numbr/ ; $num ++; } print Done. ; ? Do While 循...

php循环语句for while do while的用法.

循环结构

一、while循环

  1.  while(表达式) 
  2.  循环体;//反复执行,直到表达式为假 
  3. $num = 1; 
  4.  
  5. while ($num <= 10){ 
  6.     print "Number is $num"
  7.     $num++; 
  8. print 'Done.'
  9. ?> 

Do While 循环语句与while有一定的区别,它们的区别就是do while不管条件是否为真都会先执行一下,而while必须为真才会执行一次.

  1. do { 
  2. echo "Mmmmm...I love cookies! *munch munch munch*"
  3. while ($cookies > 1); 
  4. //输出就是. 
  5. //Mmmmm...I love cookies! *munch munch munch 

二、for循环

根据循环条件不同,有两种类型的循环

一种:计数循环(一般使用for)

另一种:条件型循环,一般使用 while do-while.

  1. for (expr1; expr2; expr3) { 
  2.   statement 

其中的 expr1 为条件的初始值,expr2 为判断的条件,通常都是用逻辑运算符号 (logical operators) 当判断的条件,expr3 为执行 statement 后要执行的部份,用来改变条件,供下次的循环判断,如加一..等等,而 statement 为符合条件的执行部分程序,若程序只有一行,可以省略大括号 {}.

下例是用 for 循环写的 "以后不敢了" 的例子,可以拿来和用 while 循环的比较,代码如下:

  1. for ($i=1; $i<=10; $i++) { 
  2.   echo "$i. 以后不敢了
    n"
  3. ?> 
  4. //输出表格 
  5.  
  6.   Value of Shares 
  7.   

    Table Showing Cost of Shares

     
  8.    
  9.    
  10.   
  11.   for ($shares = 1; $shares <= 20; $shares++){ 
  12.      $cost = $shares * 20; 
  13.      echo "The cost of $shares share/s is $cost #x0024s","n"
  14.      $dividend = $cost * 0.10; 
  15.      echo "The dividend is $dividend #x0024s  " ,"n"
  16.   } 
  17.   ?> 
  18.    
  19.    
  20.    

累加计算,代码如下:

  1.    $count = 1; 
  2.    while ($count < 5) { 
  3.       echo "$count squared = ".pow($count,2). ""
  4.        $count++; 
  5.    } 
  6. ?> 

do while 循环,代码如下:

  1.  
  2.  
  3. The <span class="keyword" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 102, 153); font-weight: bold; background-color: inherit;">do</span><span style="margin: 0px; padding: 0px; border: none; background-color: inherit;">...</span><span class="keyword" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 102, 153); font-weight: bold; background-color: inherit;">while</span><span style="margin: 0px; padding: 0px; border: none; background-color: inherit;"> Statement 
  4.  
  5.  
  6.  
  7.     $num = 1; 
  8.     do { 
  9.       print "Execution number: $numn"
  10.       $num++; 
  11.     } while ( $num > 200 && $num < 400 ); 
  12. ?> 
 
  •  
  •  
  •  
  • 分享到:
    php中 if Else 与Switch 语句对比
    在php中if Else 与Switch都是条件判断语句了,那么很多的新学php的朋友搞不清楚php中 if Else 与Switch区别在哪里,下面本文就重点介绍一下. 在网上找到一句:switch比较if具有速度优势,一个是采取转移地址列表的方法;还有就是switch一般在松散的情况下也多不采取"比较-转移 "的方法,而是用dec(sub)-jz的指令对,后者不仅是...
    php 分支结构 条件结构 选择结构
    流程控制 一、顺序结构 二、分支结构--条件结构--选择结构 1.单路分支 //条件bool,true或false,>  $b)    echo "$a 是大于 $b 的";     //双路执行   $a=10;   $b=20;   if($a>$b)   {    echo "$...
    •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
    • 在这里……