for loop in PHP

Rumman Ansari   Software Engineer   2023-03-09   5442 Share
☰ Table of Contents

Table of Content:


The for loop is used to repeat a task a set number of times.

Syntax:



for(var a_variable = initial_value; a_variable < end_value; 
a_variable_increment){ 
code to be executed;
}


Example:



<?php
for($a = 1; $a < 11; $a++){
echo $a . " ";
}
?>


Output:

This will produce the following result



1 2 3 4 5 6 7 8 9 10


The for loop has three parts:

  • variable declaration - The first part of the loop which initializes the variable at the beginning of the loop to some value. This value is the starting point of the loop.
  • condition - The second part of the loop, and it is the part that decides whether the loop will continue running or not. While the condition in the loop is true, it will continue running. Once the condition becomes false, the loop will stop.
  • increment statement - The increment statement is the third part of the loop. It is the part of the loop that changes the value of the variable created in the variable declaration part of the loop. The increment statement is the part of the loop which will eventually stop the loop from running.

Lets look at the earlier loop example step-by-step:

The code:
for($a = 1; $a < 11; $a++){ echo $a . " "; }
  • $a = 1 - The variable declaration part of the loop. A variable named a is declared with a value of 1.
  • $a < 11 - The condition of the loop. It states that as long as the variable a is less than 11, the loop should keep running.
  • $a++ - The increment statement part of the loop. It states that for every iteration of the loop, the value of the variable a should increase by 1. Recall that initially a is 1.
  • echo $a . " "; - The actual code that executes in the loop. Will print a number with a single space for each iteration in the loop.