PHP tutorial Loops

Understating PHP Loops

Beginners Tutorial


coding-zon-php-Loops

 

What is Loop,

Generally, in programming, Loops/Iterations are used to perform some repetitive tasks. 

A loop is a block of statements. And that block is executed until some fixed number of times, as specified in the condition.

PHP provides different kind of Looping statements also called Iteration statements. They can be used for different purposes such as to print group of values or reading certain number of rows from database or generating some series of numbers etc. 

 

In this tutorial, you will learn types of loops in PHP and how and when to use them? With syntax and example, they are explained.

 
 

 

Table of Contents

 

  1. While    Loop in PHP.

  2.  Do While Loop in PHP.

  3. For Loop in PHP.

  4. For-each Loop PHP.

 Go ToP↑


1. Using the while() Loop. 

Repeating set of statements until given condition is True.

When condition becomes false, it comes out of the loop. 

 

Usage ex: To read records from Database, To generate a series of numbers or To perform certain type of repetitive calculations .etc.  

 
Syntax:
 
while(condtion)
{
....
...
}
..........
...........
 

* first checks the condition and then enters into the loop. That's why it is known as entry-level checking Loop.  

 
$i = 1; //initial value
 
while ($i < 11) { // condition
print (" i = " . $i . "<br>");
$i++; //incrementation 
}
 

 If the $i value is 12. It never enters inside the loop. You will get blank output.

 
$i = 12; //initial value
 
while ($i < 11) { // condition
print (" i = " . $i . "<br>");
$i++; //incrementation 
}
 
 
 

Toc↑ 

2. Using do..while() Loop in PHP.

 

This loop first executes the block and then checks the condition. It is executed at least once before it checks the condition. It also called as exit level checking Loop.

 

This loop allows you to interact in each iteration.

 

Ex:

 

This loop can be used while producing reports etc. after generating each report It will ask you with some message like "Do you want to continue? (y/n) ". Based on the response, it will continue with the loop, or it may terminate it.

 
syntax:
  
do
{
  Something;
}
while(condition); 
 
ex:
 
$i = 6;
 
do{
 
  print $i;
 
  $i++; 
 
}while($i<=5);
 
 

GoTop↑ 

3.  for() Loop in PHP:

Used To read array values. It contains 3 parts, each part separated with ';'

 

1. Initialization

2. Condition

3, Incrementation  

 
 
syntax:
  
for(initialization; condition; incrementation)
{
.....
.....
}
 
ex:
 
for($i = 0; $i <= 10; $i++) {
 
    print $i;
}

?>
 
 

 4. For each() Loop in PHP:

This loop, generally used with arrays. You will learn more about this loop in arrays chapter.

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP