Latest web development tutorials

PHP For loop

Loop executes a block of code a specified number of times, or when a specified condition is true loop code block is executed.


for loop

for loop is used to know in advance that you need to run the script is the number of times.

grammar

for (初始值; 条件; 增量)
{
要执行的代码;
}

parameter:

  • Default:mainly initialize a variable value is used to set a counter (but can be any code is performed once at the beginning of the cycle).
  • Condition:cyclic execution constraints. If TRUE, the loop continues. If it is FALSE, the loop ends.
  • Incremental:mainly used to increment the counter (but can be any code at the end of the loop is executed).

Note: Theinitial valueandincrementparameters above can be empty or have multiple expressions (separated by commas).

Examples

The following examples define an initial value i = 1 cycle. As long as the variableiis less than or equal to 5, the loop will continue to run. Each time you run cycle, the variableiis incremented 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

foreach loop through the array is used.

Syntax

foreach ($array as $value)
{
要执行代码;
}

Once every cycle, the current value of the array element will be assigned to $ value variable (array pointer will move one by one), during the next cycle, you will see the next value in the array.

Examples

The following example shows an output value of a given array of loops:

<html>
<body>

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

</body>
</html>

Output:

one
two
three