foreach循环php
The break is a keyword that is used to stop the execution of a process after a certain number or after meeting up with particular criteria and transfers the control of the program execution to the next statement written just after the loop body.
break是一个关键字,用于在一定数量后或满足特定条件后停止进程执行,并将程序执行的控制权转移到紧接在循环体后面的下一条语句。
In this article, we will learn how to break foreach loop? To break a foreach loop means we are going to stop the looping of an array without it necessarily looping to the last elements because we got what is needed at the moment.
在本文中,我们将学习如何打破foreach循环? 中断一个foreach循环意味着我们将停止一个数组的循环,而不必循环到最后一个元素,因为此时我们已获得所需的东西。
Example 1:
范例1:
Here, we have an array of the names and breaking the loop execution when a specified string found.
在这里,我们有一个名称数组,当找到指定的字符串时,中断循环执行。
1)PHP代码演示在foreach循环中中断的示例 (1) PHP code to demonstrate example of break in a foreach loop)
<?php
// array defination
$names = array("joe", "liz", "dan", "kelly", "joy", "max");
// foreach loop
foreach ($names as $name) {
// display of the loop
echo $name . '<br>';
// stop when name is equal to dan
if ($name == 'dan') break;
}
?>
Output
输出量
joe
liz
dan
Example 2:
范例2:
Let's see how to use the break foreach using an associative array that contains the names and ages to display names and age of 2 members of the array?
让我们看看如何通过包含名称和年龄的关联数组来使用break foreach ,以显示该数组2个成员的名称和年龄?
2)PHP代码在带有关联数组的foreach循环中使用break (2) PHP code to use break in a foreach loop with an associative array)
<?php
//array definition
$members = array("joe" => "12", "liz" => "13", "sam" => "14", "ben" => "15");
//variables to count
$count = 0;
//number f display or loop
$end = 2;
foreach ($members as $key => $value) {
$count++; // increment the counter
//display
printf("%s is %d years old<br>", $key, $value);
//stop when $count equals $end
if ($count == $end) break;
}
?>
Output
输出量
joe is 12 years old
liz is 13 years old
In this example, we have defined a $count variable to count the number of loops and compare with the $end variable. The $end variable can be any number, it all depends on the number of iterations we need.
在此示例中,我们定义了$ count变量以计算循环数并与$ end变量进行比较。 $ end变量可以是任何数字,这完全取决于我们需要的迭代次数。
翻译自: https://www.includehelp.com/php/how-to-break-a-foreach-loop.aspx
foreach循环php