最干净的方法来跳过foreach如果数组为空 [英] cleanest way to skip a foreach if array is empty

查看:183
本文介绍了最干净的方法来跳过foreach如果数组为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是一个大问题,但我想知道是否有一个更干净的方式做到这一点。这将是很好,避免嵌套我的代码与一个不必要的if语句。如果 $ items 为空,php会抛出错误。

  $ items = array('a','b','c'); 

if(!empty($ items)){//< -Remove this if statement
foreach($ items as $ item){
print $ item;
}
}

我可能只是使用'@'错误抑制符

解决方案

有一百万种方法可以做到这一点。

$ b $



在其他情况下,这个方法可以使用一个数组。

  foreach((array)$ items as $ item){
print $ item;
}

注意 ,请注意,OP请求如果数组(强调是我的),跳过foreach的最干净的方式。值为true,false,数字或字符串不视为空


Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.

$items = array('a','b','c');

if(!empty($items)) { // <-Remove this if statement
  foreach($items as $item) {
    print $item;
  }
}

I could probably just use the '@' error suppressor, but that would be a bit hacky.

解决方案

There are a million ways to do this.

The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.

In other cases this is what you might need:

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.

这篇关于最干净的方法来跳过foreach如果数组为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆