PHP Loops

PHP Loops are used to execute the same block of code again and again until a certain condition is met.

Types of Loops

  • for − loops through a block of code a specified number of times.
  • while — loops through a block of code until the condition is evaluated to true.
  • do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
  • foreach − loops through a block of code for each element in an array.

for Loop

The for loop repeats a block of code until a certain condition is met. It is typically used to execute a block of code for certain number of times.

Syntax

for(initialization; condition; increment){
// Code to be executed
}

<?php
 
for($i=1; $i<=5; $i++){
    echo  $i."\n";
}
?>
Tutorials Class - Output Window

1
2
3
4
5

Run : http://ideone.com/dtOyDT


while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {
code to be executed;
}

<?php 
$n = 1; 
 
while($n <= 5) {
    echo "The number is: $n \n";
    $n++;
} 
?>

Run : http://ideone.com/e4QXjN

Tutorials Class - Output Window

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5


do…while Loop

The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.

Syntax

do {
code to be executed;
}
while (condition);

<?php 
$n = 6; 
 
do {
    echo "The number is: $n \n";
    $n++;
} while ($n <= 5);
?>

Run : http://ideone.com/PNpXXe

Tutorials Class - Output Window

The number is: 6


foreach Loop

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)
{
code to be executed;
}

<?php 
$fruits = array("mango", "apple", "papaya", "lichi"); 
 
foreach ($fruits as $value) 
{
    echo "$value \n";
}
?>

Run : http://ideone.com/tvJ0dC

Tutorials Class - Output Window

mango
apple
papaya
lichi


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a program to count 5 to 15 using PHP loop
Write a factorial program using for loop in php
Factorial program in PHP using recursive function
Write a program to create Chess board in PHP using for loop
Write a Program to create given pattern with * using for loop
Interview Questions & Answers
No Content Found.