downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

foreach> <do-while
Last updated: Sun, 25 Nov 2007

view this page in

for

for 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是:

for (expr1; expr2; expr3)
    statement

第一个表达式(expr1)在循环开始前无条件求值一次。

expr2 在每次循环开始前求值。如果值为 TRUE,则继续循环,执行嵌套的循环语句。如果值为 FALSE,则终止循环。

expr3 在每次循环之后被求值(执行)。

每个表达式都可以为空。expr2 为空意味着将无限循环下去(和 C 一样,PHP 认为其值为 TRUE)。这可能不像想象中那样没有用,因为经常会希望用 break 语句来结束循环而不是用 for 的表达式真值判断。

考虑以下的例子,它们都显示数字 1 到 10:

<?php
/* example 1 */

for ($i 1$i <= 10$i++) {
    echo 
$i;
}

/* example 2 */

for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}

/* example 3 */

$i 1;
for (;;) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}

/* example 4 */

for ($i 1$i <= 10; echo $i$i++);
?>

当然,第一个例子看上去最正常(或者第四个),但用户可能会发现在 for 循环中用空的表达式在很多场合下会很方便。

PHP 也支持用冒号的 for 循环的替代语法。

for (expr1; expr2; expr3):
    statement;
    ...
endfor;



foreach> <do-while
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
for
Steven
12-Jan-2009 02:50
Alternating form rows:

<?php

$rows
= 4;

echo
'<table><tr>';

for(
$i = 0; $i < 10; $i++){
    echo
'<td>' . $i . '</td>';
    if((
$i + 1) % $rows == 0){
        echo
'</tr><tr>';
    }
}

echo
'</tr></table>';

?>

Changing $rows will change how many columns are in a row.
dkimbel13 at gmail dot com
08-Jan-2009 07:41
Just a note on looping through an array using the for() loop.

with the array...
<?php $array = array("value1","value2","value3"); ?>

then...
<?php
for(reset($array),current($array),next($array){
    echo(
"Element ".key($array)." contains ".current($array)."<br/>";
}
?>

is the equivalent of...
<?php
for($i=0;$i<count($array);$i++){
    echo(
"Element $i contains $array[$i]<br/>");
}
?>

I don't know if there is any advantage, just thought I would mention it.
http://badluck.tv
24-Mar-2008 09:05
Nested For Loop with the same iterator as the parent.
(Well formatted so the resulting code is clean when executed).
Useful for outputting a data array into a table, ie. images.

<?php
//Dummy data
$data = array(73,74,75,76,78,79,80,81,82,83,84,85,86,87);

//Our 'stepping' variable
$g = 0;

//Our rowcount
$rowcount = 0;

echo
"<table cellspacing='0'>\r";
    for (
$i=0; $i<count($data); ) {

       
$rowcount++;
        echo
"    <tr>\r"; //New row

       
$g = $i + 3; //Set our nested limit
       
for( ; $i<$g; $i++) { //nested for loop

           
if (!isset($data[$i])) { //Allow us to break on incomplete rows
               
break;
            }

            echo
"        <td style='border: 1px #000 solid;'>\r"; //Out put a cell
           
echo "            <p>Row $rowcount <br/> Cell: $i <br/> Data: $data[$i]</p>\r";
            echo
"        </td>\r";
        }

        echo
"    </tr> \r"; //End New Row
   
}

echo
"</table>\r";?>
eduardofleury at uol dot com dot br
14-Jun-2007 09:18
<?php
//this is a different way to use the 'for'
//Essa é uma maneira diferente de usar o 'for'
for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){
   
   
$p = $i + $x;
   
    print
"\$i = $i , \$x = $x , \$z = $z <br />";
   
}

?>
lishevita at yahoo dot co (notcom) .uk
09-Sep-2006 03:33
On the combination problem again...

 It seems to me like it would make more sense to go through systematically. That would take nested for loops, where each number was put through all of it's potentials sequentially.

The following would give you all of the potential combinations of a four-digit decimal combination, printed in a comma delimited format:

<?php
for($a=0;$a<10;$a++){
    for(
$b=0;$b<10;$b++){
          for(
$c=0;$c<10;$c++){
              for(
$d=0;$d<10;$d++){
                echo
$a.$b.$c.$d.", ";
              }
           }
      }
}
?>

Of course, if you know that the numbers you had used were in a smaller subset, you could just plunk your possible numbers into arrays $a, $b, $c, and $d and then do nested foreach loops as above.

- Elizabeth
JustinB at harvest dot org
05-Aug-2005 07:23
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can.  Although many have stated this fact, most have not stated that there is still a way to do this:

<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
   
// Do Something with All Those Fun Numbers
}
?>
user at host dot com
19-Apr-2004 06:53
Also acceptable:

<?php
 
for($letter = ord('a'); $letter <= ord('z'); $letter++)
   print
chr($letter);
?>
bishop
18-Jul-2003 04:23
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:

<?php
$n
= $ITERATIONS % 8;
while (
$n--) $val++;
$n = (int)($ITERATIONS / 8);
while (
$n--) {
   
$val++;
   
$val++;
   
$val++;
   
$val++;
   
$val++;
   
$val++;
   
$val++;
   
$val++;
}
?>

(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)

That's algorithmically equivalent to the common form:

<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
   
$val++;
}
?>

$val++ can be whatever operation you need to perform ITERATIONS number of times.

On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version:       7.9857 s
Obvious version: 27.608 s
nzamani at cyberworldz dot de
18-Jun-2001 02:47
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
 
somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI
= somewhat_calcMax();
for (
$i = 0; $i <= $maxI; $i++) {
 
somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI
= somewhat_calcMax();
for (
$i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).

foreach> <do-while
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites