• Tutorial List

PHP For Loop

Last updated May 15, 2020
PHP For Loop tutorial

The PHP For Loop is used to execute a block of code for a specified number of times.

How does work the PHP For loop?

How does work the PHP For loop?

Syntax of the PHP For Loop

<?php
  for(Initialization; Condition; Increment or Decrement){
      // Statement
  }
?>

The PHP for loop takes three expressions (initialization, condition, and increment) and the expressions are separated by a semicolon (;).

  • Initialization – It is used to set the loop counter value. Basically, this expression takes a variable which value is always a number (This is the number from where the count begins).
  • Condition – The condition decides how many times the loop will run. Basically, your loop will run continuously until your condition is false.
  • Increment or Decrement – It is used to Increment or Decrement the counter value (the counter value will increase or decrease according to the number of times the loop runs.)

Example of the PHP For Loop

The following example displays the numbers from 1 to 3.

<?php
  for($variable = 1; $variable < 4; $variable++){
      echo $variable.'<br>';
  }
?>
Browser Output
1
2
3

Explanation of the above example

When the Loop Starts –

  1. $variable = 1 – First, it sets the counter value from where the count begins. The value is 1. This means that the count starts from 1.
  2. $variable < 4 – Then it checks the condition. The condition is $variable is less than 4. The $variable is 1, this means 1 is less than 4 and it is true so this loop will run.
  3. $variable++ – After that, it increase the $varriable value ($varriable + 1 = 2). To understand this, you must have to learn about PHP Increment and Decrement Operators.

Second time Loop:

  1. After increasing the $variable, Now $variable value is 2.
  2. $variable < 4 – Then it checks the condition again. Now at this time, the $variable value is 2. So our condition is – 2 is less than 4, and the condition is true so this loop will run.
  3. $variable++ – After that, it increase the $variable (2) value again ($variable + 1 = 3).

Third-time Loop:

  1. In the third time, the $variable value is 3.
  2. Then it checks the condition again, and the condition is – 3 is less than 4 and this is true so this loop will run.
  3. After that, it increase the $variable (3) value again ($variable + 1 = 4).

Fourth-time Loop:

  1. In the fourth time, the $variable value is 4.
  2. Then it checks the condition again, and the condition is – 4 is less than 4 and the condition is false so this loop will be closed.