PHP Loops

PHP Loops are use to repeat a block of code again and again up to specified number of times or infinite. In PHP, there are 4 types of loops available. They are:

PHP For loop

PHP for loop is divided into 3 parts i.e. initialization, condition and increment/decrement. Initialization is the initial value from where the loop start its execution, condition specifies the ending value of loop, if condition is true it will execute, increment/decrement will change the variable value for the next condition.

Example 1: Write a PHP program to print counting 1 to 5 using for loop

<?php
    for( $i=1; $i<=5; $i++ )
    {
        echo "<p>For Loop $i</p>" ;
    }
?>
For Loop 1
For Loop 2
For Loop 3
For Loop 4
For Loop 5

PHP While loop

PHP While loop is also used to repeat a block of code up to a certain number of times, but the syntax is different, initialization statement is defined before the while loop begins, condition appears same as in for loop, and increment/decrement statement appears inside the while loop.

Example 2: Write a program in PHP to print counting 1 to 5 using while loop

<?php
    $i=1;
    while($i<=5)
    {
        echo "<p>While Loop $i</p>";
        $i++;
    }
?>
While Loop 1
While Loop 2
While Loop 3
While Loop 4
While Loop 5

PHP Do While Loop

PHP Do...while loop is also used to repeat a block of code up to a certain number of times, but the syntax is different, initialization statement is defined before the loop begins, increment/decrement will appear inside the do while loop and condition appears in the last.

Example 3: WAP to print counting 1 to 5 using Do While Loop

<?php
    $i=1;
    do
    {
        echo "<p>Do While Loop $i</p>";
        $i++;
    }while($i<=5);
?>
Do While Loop 1
Do While Loop 2
Do While Loop 3
Do While Loop 4
Do While Loop 5

PHP foreach loop will be discuss after arrays, later in this tutorial.

Exercise Questions: Loops

  1. Create Image Gallery
  2. <?php
        for($i=1;$i<=3;$i++)
        {
            echo "<div class='col-md-4'>
                    <img src='$i.jpg'>
                </div>";
        }
    >?
    <?php
        $file = glob("images/*.jpg");
        //$file = glob("images/*");
    	$total = count($file);
    	for($i=1; $i<=$total; $i++)
    	{
    		echo "<img src='images/$i.jpg'>";
    		//$a = readdir(opendir('images'));
    		//echo "File = $a<br>";
    		
    		//$b = opendir("images");
    		//$a = readdir($b);
    		//echo "File = $a<br>";
    	}
    >?
    <?php
        echo "image gallery";
    	$b = opendir("images");
    	while($a = readdir($b))
    	{
    	if($a!='.' || $a!='..')
    		echo "<img src='images/$a'>";
    	}
    >?