110 of 110 menu

The while Loop in PHP

The while loop allows you to execute a block of code a specified number of times.

Let's use while as an example to output a string of numbers from 1 to 9. To do this, the loop must iterate 9 times.

See the example solution below, followed by an analysis:

<?php $i = 1; while ($i <= 9) { echo $i; $i++; } ?>

Code execution result:

123456789

Example Analysis

To solve the problem, a counter variable is introduced, most often called $i. This variable is assigned an initial value before the loop, in our case 1.

Then the loop termination condition is set, in our case, it is the condition $i <= 9. It means that the loop continues as long as $i is less than or equal to 9.

Inside the loop, we must increment the counter variable so that the loop eventually stops. In our case, we will increase $i by 1 using the command $i++.

See Also

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline