codecamp

PHP for循环

PHP教程 - PHP for循环

for循环由声明,条件和操作组成:

  • declaration defines a loop-counter variable and sets it to a starting value;
  • condition checks the loop-counter variable against a value;
  • action changes the loop counter.


句法

for循环的一般语法如下:

   
for ( declaration; condition; action ) { 
  // Run this code  
} 
// More code here    

实施例1

这里是一个for循环看起来在PHP:


<?php
        for ($i = 1; $i < 10; $i++) {
                print "Number $i\n";
        }
?>

上面的代码生成以下结果。

如你所见,for循环有三个部分用分号分隔。在声明中,我们将变量$ i设置为1。

对于条件,如果$ i小于10,则我们有循环执行。

最后,对于动作,我们为每个循环迭代的值$ i添加1。



实施例2

以下示例具有无限循环。

<?php
        for (;;) {
                print "In loop!\n";
        }
?>

实施例3

你可以嵌套循环,如你所愿,像这样:


<?php
     for ($i = 1; $i < 3; $i = $i + 1) {
             for ($j = 1; $j < 3; $j = $j + 1) {
                     for ($k = 1; $k < 3; $k = $k + 1) {
                             print "I: $i, J: $j, K: $k\n";
                     }
             }
     }
?>

上面的代码生成以下结果。

PHP while循环
PHP break
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Operator

Introduction

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }