8 of 110 menu

PHP While Loop Examples

The while loop allows you to execute a certain code a specified number of times. Let's study its operation with examples.

Example

Let's output a string of numbers from 1 to 9:

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

Code execution result:

123456789

Example Breakdown

To solve the problem, a counter variable is introduced, most often it is 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 runs as long as $i is less than or equal to 9.

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

Example

Let's output a column of numbers from 1 to 5. To do this, we will add the br tag during output:

<?php $i = 1; while ($i <= 5) { echo $i . '<br>'; $i++; } ?>

Example

Let's find the sum of numbers from 1 to 5. For this, a variable is introduced in which the sum will be accumulated, in our case it is the variable $sum.

To find the sum, we will each time add to this variable its current value plus the content of the variable $i:

<?php $i = 1; $sum = 0; while ($i <= 5) { $sum += $i; $i++; } ?>

Code execution result:

15

How it works: at the beginning $sum is 0, then on the first pass of the loop it becomes 0 + 1 = 1, on the next pass of the loop it becomes 1 + 2 = 3 and so on until the loop ends.

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