PHP For Loop

by Hiroshi on June 21, 2008

in For Loop, Loops, PHP Basics

For loop consists of three phases. i.e.

  • Define
  • Condition
  • Increment or decrement

First we define something. Then we apply a condition and then under that condition we increment or decrement that defined thing.

In complex way;
– The first part is an expression that is evaluated once when the loop begins.
– The second part is the condition. While the condition is true, the loop continues repeating. If the condition is false to start with, the following code block is not executed at all.
– The third part is an expression that is evaluated once at the end of each pass of the loop.

for ( initialize a counter;
       conditional statement;
       increment a counter)
{
	do this code;
}

Examples

<?php
for ($i = 1; $i <= 10; $i++)
{
    echo $i;
}
 
// Output of this script will be. 12345678910
 
// Explanation of above example:
// In this we define a var i and give it a value of 1.
// We tell the script to increment the value of i and print it.
// And keep incrementing it and printing it until it reaches to the value of 10.
// Or keep incrementing it and printing it if it is less then 10 or equal to 10.
 
// Caution:
// Now do not run a loop without a condition.
// Because it can go pretty mad without a condition.
// and go in cyclic chain process which will never end.
// and your PC or at least your PHP host will be held.
?>

Other Examples Of For Loop In PHP

<?php
for ($i = 1; $i <= 10; print $i, $i++);
 
// Output of this script will be. 12345678910
 
?>
<?php
$i = 1;
for (; ; )
{
    if ($i > 10)
   {
        break;
    }
    echo $i;
    $i++;
}
 
// Output of this script will be. 12345678910
 
?>
<?php
for ($i = 1; ; $i++)
   {
    if ($i > 10) {
        break;
    }
    echo $i;
}
 
// Output of this script will be. 12345678910
 
?>
<?php
for($num = 1; $num < 10; $num++)
{
if($num == 5)
continue;
echo "\n" . $num;
}
 
// Output of this script will be. 1 2 3 4 6 7 8 9
 
?>
<?php
for($num = 1; $num < 10; $num++)
{
if($num == 5)
break;
echo "\n" . $num;
}
 
// Output of this script will be. 1 2 3 4
 
?>

Using PHP for loop allows you to use much less code to do the same thing as with while and do.

Related Posts

Previous post:

Next post: