Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

For Loop

The PHP for Loop

The for loop is utilized when you know the exact number of times the script should execute.

Syntax

for (expression1, expression2, expression3) {
// code block
}

Here’s how it works:

  • expression1 is evaluated once.
  • expression2 is evaluated before each iteration.
  • expression3 is evaluated after each iteration.$x

Example

Output the numbers from 0 to 10:

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

Example Explained

  • The first expression, $x = 0;, is evaluated once to initialize the counter at 0.
  • The second expression, $x <= 10;, is checked before each iteration, and the code block runs only if this condition is true. In this case, the condition remains true as long as $x is less than or equal to 10.
  • The third expression, $x++;, is evaluated after each iteration, increasing the value of  by one with each cycle.

The break Statement

Using the break statement, we can exit the loop even if the condition remains true.

Example

Exit the loop when $x reaches 3:

for ($x = 0; $x <= 10; $x++) {
 if ($x == 3) break;
 echo "The number is: $x <br>";
}

The continue Statement

The continue statement allows us to skip the current iteration and move on to the next one.

Example

Skip to the next iteration if $x is 3:

for ($x = 0; $x <= 10; $x++) {
 if ($x == 3) continue;
 echo "The number is: $x <br>";
}

Step 10

This example counts to 100 in increments of ten:

Example

 for ($x = 0; $x <= 100; $x+=10) {
 echo “The number is: $x <br>”;
}