cleanest way to skip a foreach if array is empty

PhpCoding Style

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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.

Solution 3 - Php

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

if(is_array($items)) {
  foreach($items as $item) {
    print $item;
  }
}

Solution 4 - Php

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.

Solution 5 - Php

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.

Solution 6 - Php

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.

Solution 7 - Php

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

Solution 8 - Php

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

Solution 9 - Php

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.

Solution 10 - Php

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) { }
}

Solution 11 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeyoView Question on Stackoverflow
Solution 1 - PhpChristianView Answer on Stackoverflow
Solution 2 - PhpYour Common SenseView Answer on Stackoverflow
Solution 3 - PhpMatt WilliamsonView Answer on Stackoverflow
Solution 4 - PhpZach RattnerView Answer on Stackoverflow
Solution 5 - PhpDaniel KmakView Answer on Stackoverflow
Solution 6 - PhpVladislav RastrusnyView Answer on Stackoverflow
Solution 7 - PhpMilanView Answer on Stackoverflow
Solution 8 - Phpuser187291View Answer on Stackoverflow
Solution 9 - PhpswirtView Answer on Stackoverflow
Solution 10 - Phpshasi kanthView Answer on Stackoverflow
Solution 11 - PhpspetsnazView Answer on Stackoverflow