Hit enter after type your search item

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.

The code:



Using the decrement operator in while loop example

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


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 code with markup:


PHP while endwhile

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 code:


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

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 the index and values of elements are displayed.



PHP while associative array

First, an associative array is created as follows:

After that the while loop is used:

This div height required for enabling the sticky sidebar