PHP - 我应该跳出多深的循环?
PHP - How deep should I break out of the loops?
我在 PHP 中有无限循环,需要知道 switch case 中断后的整数。现在我使用 break 5;
但我现在确定这是否正确。有人能告诉我如何打破除 while (true)
之外的所有循环吗?我删除了不必要的代码,所以只剩下循环了。
$i = 0;
while (true)
{
// After the break 5 in the switch we should land here again
foreach ($users as $user)
{
while ($i < 10)
{
if (!empty($user))
{
if (isset($user->id))
{
switch($user->id)
{
case 1:
break 5;
default:
break 5; // Need to break out the foreach. So a break five right?
}
}
}
$i++;
}
}
$i=0;
}
答案是 3,因为 break 结束了当前 for、foreach、while、do-while 或 switch 结构的执行。
其中break 1
只存在switch
、2、while
和3 foreach
和 4 主要 while
.
但这也许是更好的方法,因为您可以明确说明要去哪里,而不是猜测。您不能将 goto 标记放在循环内,但在您的情况下,您可以在循环之前进行。
$i = 0;
mybegin:
while (true){
# 1. After the break 3 in the switch we will -not- land here.
# 3. So if you want to start here, you will need to use the goto statement.
foreach ($users as $user){
while ($i < 10){
if (!empty($user)){
if (isset($user->id)){
switch($user->id){
case 1:
break 3;
default:
goto mybegin;
}
}
}
$i++;
}
}
# 2. Using break 3, the code continues here.
$i=0;
}
但我不得不说,我从来不需要那么多循环或 goto 语句,因为总有更好的方法。
我在 PHP 中有无限循环,需要知道 switch case 中断后的整数。现在我使用 break 5;
但我现在确定这是否正确。有人能告诉我如何打破除 while (true)
之外的所有循环吗?我删除了不必要的代码,所以只剩下循环了。
$i = 0;
while (true)
{
// After the break 5 in the switch we should land here again
foreach ($users as $user)
{
while ($i < 10)
{
if (!empty($user))
{
if (isset($user->id))
{
switch($user->id)
{
case 1:
break 5;
default:
break 5; // Need to break out the foreach. So a break five right?
}
}
}
$i++;
}
}
$i=0;
}
答案是 3,因为 break 结束了当前 for、foreach、while、do-while 或 switch 结构的执行。
其中break 1
只存在switch
、2、while
和3 foreach
和 4 主要 while
.
但这也许是更好的方法,因为您可以明确说明要去哪里,而不是猜测。您不能将 goto 标记放在循环内,但在您的情况下,您可以在循环之前进行。
$i = 0;
mybegin:
while (true){
# 1. After the break 3 in the switch we will -not- land here.
# 3. So if you want to start here, you will need to use the goto statement.
foreach ($users as $user){
while ($i < 10){
if (!empty($user)){
if (isset($user->id)){
switch($user->id){
case 1:
break 3;
default:
goto mybegin;
}
}
}
$i++;
}
}
# 2. Using break 3, the code continues here.
$i=0;
}
但我不得不说,我从来不需要那么多循环或 goto 语句,因为总有更好的方法。