cleanest way to skip a foreach if array is empty [

2019-01-30 16:45发布

This question already has an answer here:

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.

11条回答
手持菜刀,她持情操
2楼-- · 2019-01-30 17:40

The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.

So, introducing $items as $items = array(); is what you really wanted.

查看更多
迷人小祖宗
3楼-- · 2019-01-30 17:44

I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.

All other solutions are quite dirty hacks to me.

查看更多
够拽才男人
4楼-- · 2019-01-30 17:45
foreach((array)$items as $item) {}
查看更多
等我变得足够好
5楼-- · 2019-01-30 17:46

If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:

foreach (($result ? $result : array()) as $item)
    echo $item;

Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.

查看更多
Evening l夕情丶
6楼-- · 2019-01-30 17:46

You can check whether $items is actually an array and whether it contains any items:

if(is_array($items) && count($items) > 0)
{
    foreach($items as $item) { }
}
查看更多
登录 后发表回答