PHP Loops

Updated: April 20th, 2022, 11:01:36 IST
Published: April 19th, 2022
PHP Loops
Title: PHP Loops

In this tutorial, you will learn how to use PHP loops to repeat a set of tasks. In PHP, we have the following loops: while, do...while, for and foreach.

PHP Loops

When coding, you sometimes want the same block of code to execute a specific number of times. So, rather than adding numerous almost similar code of lines to a script, we may use loops.

Loops are used to repeat the same block of code as long as a given condition is true.

  • while loops executes through a block of code as long as the specified condition is true
  • do...while loops executes through a block of code atleast once, and then repeats the loop as long as the specified condition is true
  • for loops executes through a block of code a specified number of times
  • foreach loops executes through a block of code for each element in an array

The following topics are explained with examples of each loop type.

PHP While Loop

While loops are the most basic sort of PHP loop. They act just like their C counterparts. The while loop executes through a block of code as long as... read more

PHP do-while Loop

do-while loops are very similar to while loops, except the true condition is checked at the end of each iteration instead of in the beginning. The... read more

PHP for Loop

For loops are the most complex loops in PHP. The for loop executes through a block of code a specified number of times when you know how many times... read more

PHP foreach Loop

The PHP foreach loop executes only on arrays, and is used to loop through each key/value pair in an array. The foreach loop in PHP executes through a... read more