PHP 循环 - For 循环


PHP 循环 - For 循环

FOR循环是一种用于重复执行固定次数操作的控制结构。 在PHP中,FOR结构允许我们定义循环计数器的初始值、结束条件以及步进量的规则。

何时使用循环?

通常在执行相同或相似任务的多个操作中,循环结构非常有用。无论您要处理多个变量或重复执行代码块,PHP中的循环结构是解决此类问题的有效方法。

语法

任何FOR循环包括三个基本组件:初始化、测试和操作。

for (初始化, 测试, 操作) {
  代码块
}
  • 初始化 - 初始化循环所需的条件并且在循环开始时执行。
  • 测试 - 当该条件在每次迭代之前计算并返回“true”时,执行代码块。
  • 操作 - 循环中每个迭代中用作自增器或自减器等的操作。

初始化、测试和操作在for循环的圆括号中以分号分隔。 让我们看一个例子,其中定义了一些变量,在每次循环中,计数器将增加1,直到达到定义的上限:

<?php
for ($counter = 0; $counter <= 10; $counter++) {
  echo "The counter is: $counter <br>";
}
?>

输出

The counter is: 0
The counter is: 1
The counter is: 2
The counter is: 3
The counter is: 4
The counter is: 5
The counter is: 6
The counter is: 7
The counter is: 8
The counter is: 9
The counter is: 10

在上面的示例中,初始化变量为$counter = 0,测试为$counter <= 10并且操作为$counter++。

控制循环

在FOR循环中,可以使用控制语句来控制时间和操作。

  • break语句 - 终止循环并使代码执行继续。
  • continue语句 - 终止迭代并跳转到下一个迭代。
  • goto语句 - 跳转到代码中的某个带有标签的语句。

下面是使用break语句停止循环的示例:

<?php
for ($counter = 0; $counter <= 10; $counter++) {
  if ($counter == 5) {
    break;
  }
  echo "The counter is: $counter <br>";
}
?>

输出

The counter is: 0
The counter is: 1
The counter is: 2
The counter is: 3
The counter is: 4

在上面的示例中,当$ counter == 5时,我们使用break语句停止循环。

多重循环

您可以使用嵌套的FOR循环执行多个任务,称为多重循环。 以下是具有嵌套循环的示例:

<?php
for ($i = 0; $i <= 5; $i++) {
  for ($j = 0; $j <= 3; $j++) {
    echo "The value of i is: $i, and the value of j is: $j <br>";
  }
}
?>

输出

The value of i is: 0, and the value of j is: 0
The value of i is: 0, and the value of j is: 1
The value of i is: 0, and the value of j is: 2
The value of i is: 0, and the value of j is: 3
The value of i is: 1, and the value of j is: 0
The value of i is: 1, and the value of j is: 1
The value of i is: 1, and the value of j is: 2
The value of i is: 1, and the value of j is: 3
The value of i is: 2, and the value of j is: 0
The value of i is: 2, and the value of j is: 1
The value of i is: 2, and the value of j is: 2
The value of i is: 2, and the value of j is: 3
The value of i is: 3, and the value of j is: 0
The value of i is: 3, and the value of j is: 1
The value of i is: 3, and the value of j is: 2
The value of i is: 3, and the value of j is: 3
The value of i is: 4, and the value of j is: 0
The value of i is: 4, and the value of j is: 1
The value of i is: 4, and the value of j is: 2
The value of i is: 4, and the value of j is: 3
The value of i is: 5, and the value of j is: 0
The value of i is: 5, and the value of j is: 1
The value of i is: 5, and the value of j is: 2
The value of i is: 5, and the value of j is: 3

在嵌套的FOR循环中,请注意我们在外部循环中更新$i变量,而在内部循环中更新$j变量。

结论

FOR循环是一种非常有用和常用的控制结构,在PHP中,可帮助我们执行相同或相似任务的多个操作。 我们可以使用控制语句控制循环,也可以使用多个任务的多重循环。With the help of FOR loop, we can perform mundane, time-consuming, and repetitive tasks with ease.