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:25

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. In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.

查看更多
家丑人穷心不美
3楼-- · 2019-01-30 17:25

Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.

foreach (is_array($Items) || is_object($Items) ? $Items : array()  as $Item) {

It is a bit of a pain to write, but is the safest way to handle it.

查看更多
劫难
4楼-- · 2019-01-30 17:27

I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.

查看更多
Ridiculous、
5楼-- · 2019-01-30 17:28

i've got the following function in my "standard library"

/// Convert argument to an array.
function a($a = null) {
    if(is_null($a))
        return array();
    if(is_array($a))
        return $a;
    if(is_object($a))
        return (array) $a;
    return $_ = func_get_args();
}

Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions

  foreach(a($whatever) as $item)....

  $foo = array_map(a($array_or_string)....

  etc
查看更多
做自己的国王
6楼-- · 2019-01-30 17:32

Best practice is to define variable as an array at the very top of your code.

foreach((array)$myArr as $oneItem) { .. }

will also work but you will duplicate this (array) conversion everytime you need to loop through the array.

since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

查看更多
戒情不戒烟
7楼-- · 2019-01-30 17:33
$items = array('a','b','c');

if(is_array($items)) {
  foreach($items as $item) {
    print $item;
  }
}
查看更多
登录 后发表回答