Структуры контроля


for

for loops are mainly used to iterate statement for specific number.

Синтаксис Описание
for(expr1;expr2;expr3)
{
  stmt;
}
1) expr1 is evaluated once at the beginning of the loop
2) stmt will be executed if expr2 is TRUE
3) expr3 is evaluated at the end of iteration

In general, initializing a variable is given in expr1 and conditional expression is specified in expr2. In expr3, incrementing or decrementing operation is used to determine amount of iteration.

  • Example of for
<?php
    for($i = 0; $i < 5; $i++)  // increase $i by one from 0 and compare with 5
    {
      echo $i;                 // statement is executed if $i is less than 5
    }
?>
[result]  
0
1
2
3
4

Each expression can be omitted.

  • Example of Omitting Expression 1
<?php
    for($i = 1; ; $i++)  // Omit the second expression
    {
      if($i > 10)
        break;           // Break the for loop
      echo $i;
    }
?>
[result]  
12345678910
  • Example of Omitting Expression 2
<?php
    $i = 0;
    for( ; ; )     // Omit all of expressions
    {
      if($i > 10)
        break;     // Break the for loop
      echo $i;
      $i++;
    }
?>
[result]  
012345678910
  • Combination of for and array
    for loops are very suitable for proceeding elements of an array in order.
<?php
    $arr = array(1, 2, 3);     // arr[0] = 1, arr[1] = 2, arr[2] = 3
    for($i = 0; $i < 3; $i++)  // increase $i by one from 0 and compare with 3
    {
      echo $arr[$i];           // statement is executed if $i is less than 3
    }
?>
[result]  
123