Php Loop Examples

Like any other programming language, we can define all type of loops in php, In this tutorial you will learn how to write loops in php.

for, foreach, do, while Loop in Php

What is Loop in Php?
Loop is a Control Structure that helps executing any code or logic number of times until a certain condition is satisfied.

Loop will be very useful in following situation

  • php loop through object
  • php loop comma separated list item
  • php for loop through array
  • php loop break and continue

Here you learn all type of Loops in Php with examples

Php For loop Example

for ($x = 1; $x <= 10; $x++) {
echo "The number is: $x <br>";

Result of the above for loop , loop runs till value of X is less or equal to 10

The number is: 1     
The number is: 2   
The number is: 3    
The number is: 4    
The number is: 5      
The number is: 6   
The number is: 7 
The number is: 8    
The number is: 9       
The number is: 10

Php ForEach loop example

Foreach loop will continue till the end of collection object or array

ForEach loop Syntax
$colors = array("Java", ".Net", "SQL", "LINQ","PHP", "JQuery");
foreach ($colors as $value) {
    echo "$value";

PHP While loop Example

If condition is satisfied then while loop is executed

While loop Syntax
<?php while (condition){ block of code to be executed;
$i = 0;
while ($i < 5){
    echo $i + 1 . "<br>";

PHP Do While loop Example

Do loop start executing, then when condition is satisfied then exit the loop

Do While loop Syntax
block of code to be executed }
$i = 10;
echo "$i is"." <br>";
while($i < 10);

Loop structure is almost same in every programming language, may be there are some minor syntax difference, if interested, look at loops example below in other programming language.

PHP Examples | Join PHP Online Course