PHP Basics

PHP While Loop

While loop is another best solution to handle tasks that are done in repetition. To better understand while loop you must have good understanding of for loop.

Read: PHP For Loop

While Loop

In the previous chapter, I have mentioned, before using for loop, we must have to answer following three questions.

  • What is the starting value or starting point?
  • How long should the loop continue?
  • How much the value should be incremented or decremented at the end of each loop?

Therefore this same questions are applied to while loop also. Before using while loop we must have answers to the above question.

Syntax

define starting value or point

while(condition for the loop){

//codes to perform required task in the each loop

value should increment or decrement

}

 

Whenever we use while loop, first we need to define the starting value.

Then the word “while” followed with parenthesis. In the parenthesis, we pass the condition upto when the loop should continue.

Inside the chain brackets we write the code required to perform a task in the each loop. And the most important part how much the value should increment or decrement at the end of each loop.

Example

Lets print 1 to 10 using while loop

solution

<?php

$num=1;

while($num<=10){

echo $num.'<br/>’;

$num++ // The value increments by 1 at the end of each loop.

}

?>

 

Output

1

2

3

4

5

6

7

8

9

10

Why it is so important to set the value increment or decrement inside the chain bracket?

Because, the loop begins from 1 and should continue until unless the value is less than or equal to 10. So the loop is going to continue until unless the condition is true. Here the condition is the value is less than or equal to 10.

If we do not mention whether the value should increment or decrement then the condition is true for infinite period of loop. That is, the value of $num is going to remain 1 at the end of each loop. Therefore it will result the while loop to run infinite period of time. Because the condition (value less than or equal to 10) is going to remain true for infinite period of time. In simple words, the while loop is going to run for infinite period of time. Such loops are known as infinite loop.

Therefore we must have to be very careful while using “for loop” and “while loop”.