20 of 110 menu

How to Make a PHP Loop

Using a loop, you can execute a certain piece of code a specified number of times. PHP has three loops: while, for and foreach. Let's see how to make them.

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 <= 5) { echo $i; $i++; } ?>

Code execution result:

12345

The for Loop

The for loop is similar to while, but more compact. See the example:

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

Code execution result:

12345

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