PHP for Loop

0
4KB

The for loop - Loops through a block of code a specified number of times.


The PHP for Loop

The for loop is used when you know how many times the script should run.

Syntax

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

This is how it works:

  • expression1 is evaluated once
  • expression2 is evaluated before each iteration
  • expression3 is evaluated after each iteration

ExampleGet your own PHP Server

Print the numbers from 0 to 10:

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

Example Explained

  1. The first expression, $x = 0;, is evaluated once and sets a counter to 0.
  2. The second expression, $x <= 10;, is evaluated before each iteration, and the code block is only executed if this expression evaluates to true. In this example the expression is true as long as $x is less than, or equal to, 10.
  3. The third expression, $x++;, is evaluated after each iteration, and in this example, the expression increases the value of $x by one at each iteration.

The break Statement

With the break statement we can stop the loop even if the condition is still true:

Example

Stop the loop when $x is 3:

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


The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Stop, and jump to the next iteration if $x is 3:

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

Step 10

This example counts to 100 by tens:

Example

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

PHP Exercises

Test Yourself With Exercises

Exercise:

Create a loop that runs from 0 to 9.

 ($i = 0; $i < 10; ) {
  echo $i;
}

Start the Exercise

Rechercher
Catégories
Lire la suite
Autre
PHP Shorthand if Statements
Short Hand If To write shorter code, you can write if statements on one line....
Par PHP Tutorial 2024-05-17 07:47:03 0 4KB
Autre
PHP Access Arrays
Access Array Item To access an array item, you can refer to the index number for indexed arrays,...
Par PHP Tutorial 2024-05-17 08:02:32 0 8KB
Autre
PHP Indexed Arrays
PHP Indexed Arrays In indexed arrays each item has an index number. By default, the first item...
Par PHP Tutorial 2024-05-17 08:00:38 0 5KB
Autre
PHP - $_SERVER
$_SERVER $_SERVER is a PHP super global variable which holds information about headers,...
Par PHP Tutorial 2024-05-17 08:08:50 0 7KB
Autre
PHP Delete Array Items
Remove Array Item To remove an existing item from an array, you can use...
Par PHP Tutorial 2024-05-17 08:06:22 0 7KB
Sociallez https://sociallez.com