• PHP Basics learning via PHP tutorial based on skill development
  • Make practise on Conditional Statement in PHP Language with examples
     

Tutorial of PHP Learn While, Do-While and For Loops

Learn How to manage PHP loops

In This tutorial we will try to understand the looping structure of loops' in PHP language by examples.To manage the repetitive tasks in programs we controle the task through looping structure.In this short course we will cover for,foreach and while loops.

A FOR loop is very similar to a WHILE loop in that it continues to process a block of code until a conditional statement becomes false.

The syntax of a for loop in PHP is just like we have in C Language.

		    for(initialize;condition;incrment/decrement)
		    {
		        //write code here to iterate
		    }
		        

The First Expression (initialize) executed at the begening of for loop and initilize the variable who is responsible to controle the loop structure.
At each iteration, expr2 (Condition) is evaluated. If it evaluates to TRUE, then the loop continues and the inner code are executed. If condition get FALSE, the execution of the loop ends.

An Example of PHP loops

A PHP Example to print numbers 1 to 10 through for loop.

		    for($i=1;$i<=10;$i++)
		    {
		        echo" $i ";
		    }
		        

An Example While loop

Same PHP Code to print numbers 1 to 10 through While loop is described here.

		    $i=1;
		    while($i<=10)
		    {
		        echo" $i ";
		        $i++;
		    }
		        

Here we first initialize the variable $i by one and increment it's value by one on each iteration of while loop.

How PHP break loop excution?

"Break" Statement can also be used to terminate the loop flow.

		    for ($i=0;$i<=5;$i++)
		    {
			    echo"Welcome";
			    if($i>3)
			    {
				    break;
		
		    }
		        

The For-Each Loop Syntax

For-each loop is used to work on PHP collections like array's.


		    <?php
			        $myarray = array(
							    '12',
							    '22',
							    '31',
							    '40',
							    '51',
							    '93'
						    );
			        foreach($myarray as $arr)
			        {
				    echo $arr."
"; } ?>

So through foreach we can efficiantly handle the collections.

Software Training & Solution Provider
258,Katewa Nagar,Jaipur,Rajasthan.
Ph: 9829708506 , 0141-4108506 , 08432830240, 8432706556

09829708506 , 08432830240