Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP for loop


May 11, 2021 PHP


Table of contents


PHP Loop - for Loop


Loop the block of code a specified number of times, or when the specified condition is true.


For loop

The for loop is used when you know in advance how many times the script needs to run.

Grammar

for ( Initial value; condition; increment )
{
The code to be executed;
}

Parameters:

  • Initial value: Primarily initializes a variable value to set a counter (but can be any code that is executed once at the beginning of the loop).
  • Condition: A restriction that is executed in a loop. I f true, the loop continues. If false, the loop ends.
  • Increment: Is primarily used for incremental counters (but can be any code executed at the end of the loop).

Note: The initial value and increment parameter above can be empty or have multiple expressions separated by commas.

Instance

The following example defines a loop with an initial value of i-1. T he loop continues to run as long as the variable i is less than or equal to 5. Each time the loop runs, the variable i increments by 1:

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5


Foreach loop

The foreach loop is used to traverse an array, looping blocks of code based on each element in the array.

Syntax

foreach ($ array as $ value )
{
To perform code;
}

Each time you loop, the value of the current array element is assigned to the $value variable (the array pointer moves one by one), and on the next loop, you will see the next value in the array.

Instance

The following example demonstrates a loop that outputs the value of a given array:

<html>
<body>

<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>

</body>
</html>

Output:

one
two
three

Note: foreach can only be applied to arrays and objects, and if you try to apply variables to other data types, or if you do not initialize variables, an error message is issued.