HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP for Loop


The for loop in PHP is a fundamental control flow structure that allows you to execute a block of code repeatedly, a specific number of times.


Syntax


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

This is how it works:

expression1 is evaluated once
expression2 is evaluated before each iterarion
expression3 is evaluated after each iterarion


Example


Print the numbers from 0 to 10:

<!DOCTYPE html>
<html>
<body>

<?php  
for ($x = 0; $x <= 10; $x++) {
  echo "The number is: $x 
"; } ?> </body> </html>

Output

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

Explained


The first expression, $x = 0;, is evaluated once and sets a counter to 0.
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.
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

The break statement is a control flow statement used in looping constructs (like for, while, do-while, and foreach) and switch statements in various programming languages, including PHP:

Example


<!DOCTYPE html>
<html>
<body>

<?php  
for ($x = 0; $x <= 10; $x++) {
  if ($x == 3) break;
  echo "The number is: $x 
"; } ?> </body> </html>

Output

The number is: 0
The number is: 1
The number is: 2

• The continue Statement

the continue statement serves a specific purpose within looping constructs.

Example


<!DOCTYPE html>
<html>
<body>

\<?php  
for ($x = 0; $x <= 10; $x++) {
  if ($x == 3) continue;
  echo "The number is: $x 
"; } ?> </body> </html>

Output

The number is: 0
The number is: 1
The number is: 2
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10