Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 8 / 68

Loops (while statements)

In this lesson you will learn how to repeat work with a while statement in PHP and how to tell it apart from a for statement. This is for anyone searching for "PHP while loop how to use".

A while statement repeats as long as its condition holds. The rule of thumb is to use a for loop when you already know the stopping point and a while loop when you do not. Just remember to update the variable the condition depends on inside the loop.

The sample code repeats while $i is 5 or less, increasing the value by one with $i++; inside the loop. The condition is evaluated at the top of every pass, and the moment it becomes false the loop exits and execution moves on.

A common stumbling block for beginners is forgetting that update and ending up in an infinite loop. When you actually want an endless loop, the standard pattern is while(true) with a break to leave it - worth knowing both.

It shines wherever the number of repetitions cannot be predicted, such as accepting user input continuously or searching until a condition is met. While loops are common in batch jobs and command-line tools too.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)