PHP Loop -For Loop


Loops execute a block of code a specified number of times, or execute a block of code repeatedly when a specified condition is true.


for loop

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

Syntax

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

Parameters:

  • Initial value: Mainly initializes a variable value to set a counter (but can be any code that is executed once at the start of the loop).
  • Condition: The limiting condition for loop execution. If TRUE, the loop continues. If FALSE, the loop ends.
  • Increment: Mainly used to increment the counter (but can be any code that is executed at the end of the loop).

Note:The aboveinitial valueandincrementparameters can be empty, or have multiple expressions (separated by commas).

Example

The example below defines a loop with an initial value of i=1. As long as the variableiis less than or equal to 5, the loop will continue to run. Each time the loop runs, the variableiincrements by 1:

Example

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

Output:

数字为 1
数字为 2
数字为 3
数字为 4
数字为 5


foreach loop

The foreach loop is used to iterate over arrays.

Syntax

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

For each iteration, the value of the current array element is assigned to the $value variable (the array pointer moves one by one). During the next iteration, you will see the next value in the array.

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

For each iteration, the key and value of the current array element are assigned to the $key and $value variables (the array pointer moves one by one). During the next iteration, you will see the next key and value in the array.

Example

The example below demonstrates a loop that outputs the values of a given array:

Example

<?php $x=array("Google","Example","Taobao"); foreach ($x as $value) { echo $value . PHP_EOL; } ?>

Output:

Google
Example
Taobao

The example below demonstrates a loop that outputs the keys and values of a given array:

Example

<?php $x=array(1=>"Google", 2=>"Example", 3=>"Taobao"); foreach ($x as $key => $value) { echo "key is" . $key . ", the corresponding value is". $value . PHP_EOL; } ?>

Output:

key  为 1,对应的 value 为 Google
key  为 2,对应的 value 为 Example
key  为 3,对应的 value 为 Taobao
Other Extensions