pTutorial

New way to learn PHP

PHP while loop

While loop

The expression inside the parentheses is tested; if it evaluates to true, the code block inside the braces is executed. Then the expression is tested again if at any point the expression return false, the loop exits.


  • While loop will execute block of code until certain condition is met
  • Function of while loop do a task again and again(as yours condition)

Flow chart

php tutorial | ptutorial

Syntax of while loop

While ( $expression )
{
code to be executed;
}

Illustrate with example

<?php

$i=0;

while($i<=7) 
{

  echo "welcome to php ";
  echo $i." time"."
"; $i++; } ?>

In the above example, first assign the value of $i=0 and after that checks $i less than 7, yes, it will be executed first time and check again if it find true then again it will be executed, if any point of time the expression return fails, the loop will be terminated

Note: There must use the same expression (that are used in a while condition ) in while loop body otherwise loop will be never terminated. This type of the unterminated loop is called infinite loop.

More While loop example

<?php

$var=1;
echo "The multiplication table :
"; while($var < 11) { echo "12 x $var =".($var*12)."
"; $var++; } ?>

In the above example, the while loop will be executed 10 times and print the table of 12.

Example

<?php

$array = array('Audi' => ' A4', 
			'Bmw' => 'X5', 
			' Lamborghini ' => '5-95 Zagato', 
			'Maruti' => ' Aulto 800', 
			);
			echo "Car->";
			echo "MOdel"."
"; reset($array); while (list($key, $value) = each($array)) { echo "$key->"; echo "$value"."
"; } ?>

Do while loop loop are explained in next section.


QUOTES OF THE DAY

Wicked men obey from fear, good men from love

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER