不是什么大问题,但我想知道是否有更干净的方法来做这件事.最好避免使用不必要的if语句嵌套我的代码.如果$items
为空,php将抛出错误.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
我可能只需要使用"@"错误 suppress 器,但这会有点不方便.
不是什么大问题,但我想知道是否有更干净的方法来做这件事.最好避免使用不必要的if语句嵌套我的代码.如果$items
为空,php将抛出错误.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
我可能只需要使用"@"错误 suppress 器,但这会有点不方便.
有一百万种方法可以做到这一点.
第一个方法是,假设您确实有一个数组,那么无论如何都要通过foreach来运行该array.
在其他情况下,这是您可能需要的:
foreach ((array) $items as $item) {
print $item;
}
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.
In addition, this would work with objects implementing \Traversable
, whereas is_array
wouldn't work.