Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP For Loop

PHP Loops - For Loop


Loop to execute a code block a specified number of times, or while 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:

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 variable i is less than or equal to 5, the loop will continue to run. Each time the loop runs, the variable i increments by 1:

Example

Output:

数字为 1

数字为 2

数字为 3

数字为 4

数字为 5


foreach Loop

The foreach loop is used to iterate over arrays.

Syntax



foreach ($array as $value)

{

    要执行代码;

}

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



foreach ($array as $key => $value)

{

    要执行代码;

}

Each time the loop runs, the key and value of the current array element are assigned to the $key and $value variables (the numeric pointer moves one by one); when the next loop runs, you will see the next key and value in the array.

Example

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

Example

Output:

Google

Runoob

Taobao

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

Example

" Google " , 2 => " Runoob " , 3 => " Taobao " ) ; foreach ( $x as $key => $value ) { echo " key is " . $key . " , corresponding value is " . $value . PHP_EOL ; } ?>

Output:

key  为 1,对应的 value 为 Google

key  为 2,对应的 value 为 Runoob

key  为 3,对应的 value 为 Taobao