PHP for loop

PHP for loop executes repeatedly same set of instructions until a termination condition is met. Sometimes we need to work with same types of code hundred to thousands time. In that case we need to write same type of code thousands time. It is a problem. To solve this problem PHP introduce for loop where we set just upper and lower condition.

PHP for loop structure: 


Here is the general form of the for statement

for(initialization; condition; iteration)
{
// Body
}


The for loop operates as follows: 
Initialization: PHP for loop starts with initialization and initialization parts is only executed one time.
Condition: It returns true or false. Condition part test the loop. If it returns true then the body of the loop is executed otherwise it exits from the loop.
Iteration: It increment or decrement the counter value (We a assume counter value which control the loop). First the loop test the condition and then execute the body and then execute the iteration and it repeats until the condition is false.

PHP for loop example: 

Now lets try an example with PHP for loop. Suppose, we want to add each value from 1 to 100. So the loop starts with 1 and ends when the value is 100.
<?php

$sum=0; 
for($count=1; $count<=100; $count++)
{
$sum=$sum+$count;
}
echo $sum;
?>

PHP nested for loop:

Nested means we put a loop inside another loop. Try to understand the following code which describe the PHP nested loop.
<?php
for($count=1; $count<10; $count++){
    for($x=$count; $x<10;$x++){
    echo "#";
    }
    echo "<br>";
}
?>
Output of this code is:
#########
########
#######
######
#####
####
###
##
#

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP