PHP Loop

The four type of loop statements are supported by PHP. They are:

  • while
  • do-while
  • for
  • foreach

while loop

while loop executes the block of code until the condition or expression return false.

Syntax:

If the condition is TRUE then the PHP code inside the block will be executed.

Example

In the above example, we have declared PHP variable $i. Every time the while loop will check if the given condition $i <= 10 is TRUE or Not.
If the condition is TRUE then inside the block, the PHP code echo $i . "<br />"; $i++; will be executed. echo is used to print the variable in the browser. And <br /> is used for line breaks to be visible in the browser.

Click the below button to see the demo of above example.
Demo

do-while loop

do-while loop is same like while loop, the differentiation is that do-while evaluate the condition at the end of every loop, whereas while loop checks the condition at first.

Syntax:

Example

Click the below button to see the demo of above example.
Demo

for loop

for loop in PHP is same as C language. Every for loop should have three expressions, first one is for declaration, second one is for to check the condition and third expression is for increment or decrement the declare_variable.

Syntax:

Example

Click the below button to see the demo of above example.
Demo

foreach loop

The foreach loop is used to iterate arrays and objects. In the first iteration first array element will be placed and the loop will last until all elements will be placed.

Syntax:

Example

Instead of "$key => $value" we can use "$value" like foreach($array as $value) if we don't want the $key value.

Click the below button to see the demo of above example.
Demo

we can re-write the above example as following, both will provide the same output.

Example

Click the below button to see the demo of above example.
Demo

Please follow and like us:
error

Leave a Reply

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