PHP Loops

PHP Loop: For, While, Do While And Foreach

Posted by

PHP loops are used to execute a statement or a statement block, multiple times until and unless a specific condition is fulfilled. This helps the programmer to save time as well as effort to write the same code several times.

Following four are the PHP loop types:

PHP for Loop:

The PHP for loop repeats a block of code until a certain condition has been met. It’s usually used for a certain number of times to execute a block of code.

Syntax:

Initialization: It is used to set the loop counter.

Condition: It decides how long the loop counter will last.

Increment/Decrement: It updates the loop counter by increment and decrement value at the end of the iteration.

Example: Let’s print numbers from 1 to 10.

In the above example, the code is initialized by 1($i = 1), the loop is running till 10 ($i <= 10) and the loop counter is updating by 1 ($i++).

Example: Let’s print a table of 2.

You can check Print Stars Pattern In PHP article to understand the for loop.

PHP while loop:

PHP while loop is also a loop like for. It checks the condition ($i <= 10) at the initial.

Syntax:

Example:

In the above example,
$i = 1; – Initialize the counter loop ($i), and set the start value to 1.
$i <= 10 – Continue the loop, as long as $i is equal to or below 10.
$i++; – For each iteration increase the loop counter value by 1.

PHP do-while loop:

Do-while loops are very similar to while loops, except that the truth expression is checked at the end of each iteration, rather than at the start. The main difference from regular while loops is that you are guaranteed to run the first iteration of a do-while loop.

Syntax:

Example:

In the above example,
$i = 1; – Initialize the counter loop ($i), and hold the value 1. First, execute the code inside do.
$i <= 10) – It check while condition($i <= 10).
So the given code executes 10 times.

PHP foreach loop:

The PHP foreach loop works on array or object. It provides an easy way of iterating an array of elements.

Syntax:

Example:

In the above example, an array defines five elements and uses foreach to access an array element’s value.

 

Please write comments if you have any queries or more information about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *