Php 简明教程

PHP - For Loop

程序默认情况下会按照语句的顺序进行执行。如果程序流被定向到程序中的任何早期语句,它就构成了循环。PHP 中的 for 语句是构成 PHP 脚本中循环的便捷工具。在本节中,我们将讨论 PHP 的 for 语句。

A program by default follows a sequential execution of statements. If the program flow is directed towards any of earlier statements in the program, it constitutes a loop. The for statement in PHP is a convenient tool to constitute a loop in a PHP script. In this chapter, we will discuss PHP’s for statement.

Flowchart of "for" Loop

以下流程图说明了 for 循环的工作原理——

The following flowchart explains how a for loop works −

php for loop

for 语句用于在你已知想要执行语句或语句块的次数时。

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax of "for" Loop

PHP 中 for 语句的语法与 C 语言中的 for 语句类似。

The syntax of for statement in PHP is similar to the for statement in C language.

for (expr1; expr2; expr3){
   code to be executed;
}

for 关键字后面是圆括号,圆括号内包含三个用分号分隔的表达式。这三个表达式各自可以为空,也可以包含多个用逗号分隔的表达式。括号后面是一条或多条放在大括号中的语句。这些语句构成了循环体。

The for keyword is followed by a parenthesis containing three expressions separated by a semicolon. Each of them may be empty or may contain multiple expressions separated by commas. The parenthesis is followed by one or more statements put inside curly brackets. It forms the body of the loop.

括号中的第一个表达式只在循环开始时执行。它通常充当 initializer ,用于设置循环迭代计数器的起始值。

The first expression in the parenthesis is executed only at the start of the loop. It generally acts as the initializer used to set the start value for the counter of the number of loop iterations.

在每次迭代的开始,都会计算 expr2 。如果计算结果为真,则循环继续并且执行主体块中的语句。如果计算结果为假,则循环执行结束。通常, expr2 指定计数器的最终值。

In the beginning of each iteration, expr2 is evaluated. If it evaluates to true, the loop continues and the statements in the body block are executed. If it evaluates to false, the execution of the loop ends. Generally, the expr2 specifies the final value of the counter.

expr3 在每次迭代的末尾执行。在大多数情况下,此表达式会递增计数器变量。

The expr3 is executed at the end of each iteration. In most cases, this expression increments the counter variable.

Example

for 循环的最一般示例如下 -

The most general example of a for loop is as follows −

<?php
   for ($i=1; $i<=10; $i++){
      echo "Iteration No: $i \n";
   }
?>

以下是它的 @{s0}

Here is its output

Iteration No: 1
Iteration No: 2
Iteration No: 3
Iteration No: 4
Iteration No: 5
Iteration No: 6
Iteration No: 7
Iteration No: 8
Iteration No: 9
Iteration No: 10

An infinite "for" loop

请注意,括号中的所有三个表达式都是可选的。仅含两个分号的 for 语句构成一个无限循环。

Note that all the three expressions in the parenthesis are optional. A for statement with only two semicolons constitutes an infinite loop.

for (; ;) {
   Loop body
}

要停止无限迭代,您需要在循环体中使用 break 语句。

To stop the infinite iteration, you need to use a break statement inside the body of the loop.

A decrementing "for" loop

您还可以形成递减 for 循环。为了创建一个从 10 到 1 的 for 循环,请用 10 初始化循环变量,在每次迭代开始时计算的中间表达式检查它是否大于 1。在每次迭代末尾执行的最后一个表达式应该递减它 1。

You can also form a decrementing for loop. To have a for loop that goes from 10 to 1, initialize the looping variable with 10, the expression in the middle that is evaluated at the beginning of each iteration checks whether it is greater than 1. The last expression to be executed at the end of each iteration should decrement it by 1.

<?php
   for ($i=10; $i>=1; $i--){
      echo "Iteration No: $i \n";
   }
?>

它将生成以下 output

It will produce the following output

Iteration No: 10
Iteration No: 9
Iteration No: 8
Iteration No: 7
Iteration No: 6
Iteration No: 5
Iteration No: 4
Iteration No: 3
Iteration No: 2
Iteration No: 1

Using the "for…endfor" construct

您还可以使用冒号 (:) 符号来启动循环块,并在块的末尾放置 endfor 语句。

You can also use the ":" (colon) symbol to start the looping block and put endfor statement at the end of the block.

<?php
   for ($i=1; $i<=10; $i++):
      echo "Iteration No: $i \n";
   endfor;
?>

Iterating an indexed array using "for" loop

数组中的每个元素都由以 "0" 开头的递增索引标识。如果存在一个包含 5 个元素的数组,则它的下限为 0,上限为 4(数组大小 -1)。

Each element in the array is identified by an incrementing index starting with "0". If an array of 5 elements is present, its lower bound is 0 and is upper bound is 4 (size of array -1).

要获得数组中的元素数量,有一个 count() 函数。因此,我们可以使用以下 for 语句遍历索引数组 -

To obtain the number of elements in an array, there is a count() function. Hence, we can iterate over an indexed array by using the following for statement −

<?php
   $numbers = array(10, 20, 30, 40, 50);

   for ($i=0; $i<count($numbers); $i++){
      echo "numbers[$i] = $numbers[$i] \n";
   }
?>

它将生成以下 output

It will produce the following output

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Iterating an Associative Array Using "for" Loop

PHP 中的关联数组是键值对的集合。箭头符号 (⇒) 用于显示键与其值之间的关联。我们使用 array_keys() 函数获取键的数组。

An associative array in PHP is a collection of key-value pairs. An arrow symbol (⇒) is used to show the association between the key and its value. We use the array_keys() function to obtain array of keys.

下面的 for 循环从代码中定义的关联数组 $capitals 中打印每个州的首府 -

The following for loop prints the capital of each state from an associative array $capitals defined in the code −

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai",
      "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow",
      "Tamilnadu"=>"Chennai"
   );
   $keys=array_keys($capitals);

   for ($i=0; $i<count($keys); $i++){
      $cap = $keys[$i];
      echo "Capital of $cap is $capitals[$cap] \n";
   }
?>

以下是它的 @{s0}

Here is its output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

Using Nested "for" Loops in PHP

如果在现有循环的体内使用另一个 for 循环,则这两个循环就被称为嵌套的。

If another for loop is used inside the body of an existing loop, the two loops are said to have been nested.

对于外部循环的计数器变量的每个值,内部循环的所有迭代都已完成。

For each value of counter variable of the outer loop, all the iterations of inner loop are completed.

<?php
   for ($i=1; $i<=3; $i++){
      for ($j=1; $j<=3; $j++){
         echo "i= $i j= $j \n";
      }
   }
?>

它将生成以下 output

It will produce the following output

i= 1 j= 1
i= 1 j= 2
i= 1 j= 3
i= 2 j= 1
i= 2 j= 2
i= 2 j= 3
i= 3 j= 1
i= 3 j= 2
i= 3 j= 3

请注意,字符串是一种数组形式。 strlen() 函数给出字符串中的字符数量。

Note that a string is a form of an array. The strlen() function gives the number of characters in a string.

Example

下面的 PHP 脚本使用两个嵌套循环在每行打印一个字符串中递增数量的字符。

The following PHP script uses two nested loops to print incrementing number of characters from a string in each line.

<?php
   $str = "TutorialsPoint";
   for ($i=0; $i<strlen($str); $i++){
      for ($j=0; $j<=$i; $j++){
         echo "$str[$j]";
      }
      echo "\n";
   }
?>

它将生成以下 output

It will produce the following output

T
Tu
Tut
Tuto
Tutor
Tutori
Tutoria
Tutorial
Tutorials
TutorialsP
TutorialsPo
TutorialsPoi
TutorialsPoin
TutorialsPoint