Loops
In this tutorial we will study about Loops in php and learn
how we can use it for different purposes. So let start by asking a simple
question i.e. what is a loop? In general
English we say a loop is doing same things again and again until we satisfied
with the result.
For e.g. listen a music repeatedly, switching on and off of
the fan
Now in php we have
four syntax are there using which can instruct the php to execute bunch
of statements again and again. So let
see what they are?
a) for loop
b) while loop
c) do-while loop
d) do loop
a) for loop
b) while loop
c) do-while loop
d) do loop
Now we will looking the most used loops which are “for” and
“while” loops.
FOR LOOP
first of all let know about syntax i.e. how we can write the loop
syntax:
for(initialization ; condition ; increment/decrement)
{
//body goes here
}
let start with simple understanding:
for: This thing refers to the English word “for”.
Initialization: This refers to the first value of the variable to which it is
initialized.
condition: This is the condition using which a loop continue its work i.e. if the
condition will be true than loop will continue but if false than loop will be break
out.
Increment/decrement: This part of the loop is used to bring the value of
the variable to the condition to value on which the loop will stop iterating.
Now let’s take an example of for loop:
first of all let know about syntax i.e. how we can write the loop
syntax:
for(initialization ; condition ; increment/decrement)
{
//body goes here
}
let start with simple understanding:
for: This thing refers to the English word “for”.
Initialization: This refers to the first value of the variable to which it is
initialized.
condition: This is the condition using which a loop continue its work i.e. if the
condition will be true than loop will continue but if false than loop will be break
out.
Increment/decrement: This part of the loop is used to bring the value of
the variable to the condition to value on which the loop will stop iterating.
Now let’s take an example of for loop:
<?php
for( $i = 0 ; $i <= 10 ; $i++){
for( $i = 0 ; $i <= 10 ; $i++){
echo
$i.” ”;
}
Output : 0 1 2 3 4 5 6 7 8 9 10
WHILE LOOP
The working of this loop is same as it as FOR loop but the syntax is differed. Let’s see the syntax:
SYNTAX:
Initialization
while(condition){
//Statements or body
increment/decrement
}
eg.
$i=0;
while ($i<=10) {
echo $i;
$i++; }
Output : 0 1 2 3 4 5 6 7 8 9 10
Output : 0 1 2 3 4 5 6 7 8 9 10
WHILE LOOP
The working of this loop is same as it as FOR loop but the syntax is differed. Let’s see the syntax:
SYNTAX:
Initialization
while(condition){
//Statements or body
increment/decrement
}
eg.
$i=0;
while ($i<=10) {
echo $i;
$i++; }
Output : 0 1 2 3 4 5 6 7 8 9 10