PHP For Loop

The for loop in PHP is a versatile tool for running a block of code a specified number of times. It’s ideal when the number of iterations is predetermined.

Tutorials dojo strip

Syntax

PHP
  • Initialization: Executes once at the start, setting the initial state.
  • Condition: Checked before every iteration; the loop runs as long as this evaluates to true.
  • Increment: Executes after each iteration, often used to update the counter variable.

Example: Motorcycle Model Numbers

This example displays motorcycle model numbers from 0 to 10:

PHP

Explanation:

  1. $model = 0; initializes the counter variable $model to 0, establishing the starting point of the loop.
  2. $model <= 10; checks whether the value of $model is less than or equal to 10 before each iteration. If true, the loop proceeds; otherwise, it stops.
  3. $model++; increments the counter variable $model by 1 after each loop iteration, allowing the loop to advance towards its stopping point.

This ensures that the script outputs all motorcycle model numbers from 0 to 10 in sequence.

The break Statement

The break statement can be used to terminate the loop early. For instance, stop the loop when the motorcycle model reaches 3:

PHP

The continue Statement

The continue statement allows skipping the current iteration and moving on to the next. In this example, skip the model corresponding to Honda (represented as 3):

PHP

Custom Increment Steps

You can modify the increment value to suit specific needs. For example, count motorcycle production batches in steps of 10:

PHP

Tutorials dojo strip