46 of 110 menu

PHP Loops Examples

The while Loop

The while loop will execute as long as the expression passed to it as a parameter is true. See the example:

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

Code execution result:

123456789

The for Loop

The for loop is an alternative to while. It is more complex to understand, but most often it is preferred over while because it takes up fewer lines. See the example:

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

Code execution result:

123456789

The foreach Loop

The foreach loop is used to iterate through all elements of an array. See the example:

<?php $arr = [1, 2, 3, 4, 5]; foreach ($arr as $elem) { echo $elem; }; ?>

Code execution result:

12345

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