这里我是否需要使用break语句,或者它会自动停止循环并直接返回?
for($i = 0; $i < 5; $i ++) {
if($var[$i] === '') return false;
// break;
}
感谢您!它将运行一次,停止循环并从函数/方法退出。
然而,可以争论这是不好的风格。稍后很容易忽略return
,这对调试和维护不利。
使用break
可能更清晰:
for($i = 0; $i < 5; $i ++) {
if($var[$i] === '')
{ set_some_condition;
break;
}
}
if (some_condition)
return;
更新:
PHP 7需要一个return
。因为循环在return
时结束,所以不需要break;
。
在switch或loop中,break;
通常用于找到所需的项。
例子:
$items = ['a' , 'b' , 'c'];
foreach($items as $item)
{
if($item == 'a')
{
return true; // the foreach will stop once 'a' is found and returns true.
}
return false; // if 'a' is not found, the foreach will return false.
}
或者:$items = ['a' , 'b' , 'c'];
foreach($items as $item)
{
return $item == 'a'; // if 'a' is found, true is returned. Otherwise false.
}
如果使用return
,则函数(或整个脚本)将返回——此后的所有代码都不会被执行。因此回答你的问题:这里不需要break
。但是,如果在这里没有注释掉break
,循环将在一次迭代后停止。这是因为你的if语句没有使用大括号({...}
),因此它只包含了return
语句(换句话说:你示例中的break
总是会被执行)。
return
works . Simple example :`$items = ['a' , 'b' , 'c'];foreach($items as $item) {echo $item; if($item == 'a') return true;
}` - EGurelliforeach()
没有任何意义 - 可以简单地写成return $items[0] == 'a';
。 - mickmackusa