PHP Syntax Statements Looping for

 

- Info:

- Depending on the condition, for statement can execute specified code mutliple times.

- expression1 is executed at the begining of the first iteration.

- condition is evaluated at the begining of each iteration.

If it evaluates to TRUE code is executed.

If it evaluates to FALSE code is NOT execued and program breaks out of for loop.

- expression2 is executed at the end of each iteration.

- Both expressions and condition can be left empty in which case condition evaluates to TRUE.

You can break out of such for loop by using conditional and break statement inside a code.

 

- Syntax:

for (expression1;condition;expression2) { code }

 

- Example:

- Create PHP Console Application Test.php.

 

Test.php

<?php

 

#SIMPLE. Output is: 1234.----------------------------------------------

for($i=1;$i<=4;$i++){

print($i);

}

#COMPLEX. Output is: 123.-----------------------------------------------

for($i=1, $j=5 ; $i<=4 && $j>2 ; $i++,$j--){

print($i);

}

#BREAK. Output is: 12 since we break out of for loop when $i=3.-----

for($i=1;$i<=4;$i++){

if($i==3) { break; }

print($i);

}

#CONTINUE. Output is: 124 since display of number 3 is skipped.----------

for($i=1;$i<=4;$i++){

if($i==3) { continue; }

print($i);

}

 

#EMPTY. Output is: 1234 since we break on 5.-----------------------------

$cnt = 0;

for(;;){

$cnt++;

if($cnt==5) { break; }

print($cnt);

}

 

 

?>