Search code examples
phpcoding-style

cleanest way to skip a foreach if array is empty


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.


Solution

  • 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.