PHP for Loop

Updated: April 20th, 2022, 08:33:35 IST
Published: April 20th, 2022
PHP for Loop
Title: PHP for Loop

For loops are the most complex loops in PHP. The for loop executes through a block of code a specified number of times when you know how many times the script should run ahead of time.

PHP for Loop

Syntax

for (init counter; test counter; increment counter) {
  code to be executed for each iteration;
}

Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Example

The example below shows the numbers from 0 to 10:

<?php
for ($n = 0; $n <= 10; $n++) {
  echo "The number is: $n <br>";
}
?>

Example Explained

  • $n = 0; - Initialize the loop vatiable ($n), and set the value to 0
  • $n <= 10; - Continue the loop as long as $n is less than or equal to 10
  • $n++ - Increase the loop variable value by 1 for each iteration