The while loop in PHP

What is while loop?

The PHP while loop is used to execute a given block of code until the given expression in the while is false.

This is the simplest type of loop in PHP that works just like C language.

The condition or value of the expression is checked at the beginning of the while loop.

See also: the for loop

Structure of while loop

Following is the general structure of using the while loop in PHP programs:

 

As expression is evaluated at the beginning of while loop, if the condition is false upfront, the statements inside the curly braces will not execute. In order to execute the block of code at least once, even the condition is false, you may use the do..while loop.

An example of using the while loop to display numbers

In this simple example of using the while loop in PHP; a variable is assigned an initial value. The value of the variable is checked in each iteration and incremented by 1 if the condition is true.

PHP while

See online demo and code

This is how the while loop is used in above example:

 

Using the decrement operator in while loop example

In this example, the value of the variable is decremented in each iteration and displayed in an HTML div.

PHP while decrement

See online demo and code

The following code for while loop is used in this example:

 

Using endwhile keyword in while loop

You may use the endwhile keyword as well in the while loop. This example will output the same as in the first example:

PHP while endwhile

See online demo and code

This is how the endwhile is used in above example:

 

A demo of incrementing by more than one in while loop

In above examples, the increment or decrement of the variable’s value is 1 by using the ++ or –. You may specify other values. In this example, the increment in each iteration is 10.

PHP while increment 10

See online demo and code

The following code is executed:

 

Using while loop with PHP arrays

You may use the PHP while loop with arrays as well. In this example, an array of five elements is created. The expression in the while loop is the total length of elements by using the count function. So, the while loop will keep on executing until it reaches the maximum length of the array. In each iteration, the value of the current element is displayed by using the echo statement of PHP.

PHP while array

See online demo and code

This is how array elements are displayed by using the while loop:

 

An example of using while loop with associative array

In this example, an associative array of three elements is created. A while loop is used with key/value where index and values of elements are displayed.

PHP while associative array

See online demo and code

First, an associative array is created as follows:

 

After that the while loop is used: