PHP For Loop


For loop is an entry-controlled loop which consists of initialization, condition and increment/decrement.

The execution of the for loop statement is 3 parts:

  • Initialization
  • Test-condition
  • Increment or Decrement

1. Initialization:

Control variable is initialize one time at first. To declare and initialize any loop control variables.


2. Test-condition:

If the test condition is true, the body of the loop is executed otherwise the loop is terminated.


3. Increment or Decrement:

When the body of the loop is executed, the control is transferred back to the increment statement.


Syntax:-

for ( initialization ; test-condition ;increment)
{
    Body of the loop
} 

Example:-

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

PHP foreach Loop

It is used to traverse arrays or collections in PHP. You don't need to use an increment variable in the PHP foreach loop.

Syntax:-

for(Type var:array){   
   // Body of the loop
} 

Example:-

<?php
$arr = [1, 2, 3, 4, 5];

// Printing array using foreach loop
foreach ($arr as $i) {
    echo $i . "\n";
}
?>

PHP Nested Loop

We can use Nested For loop as For loop inside another For loop. The inner loop is executed completely when the outer loop is executed one time. If the outer loop executed 3 times then the inner loop also executed 3 times.


PHP Infinite Loop

In this, we can use double semicolons and it will be executed infinite times.




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.