views:

266

answers:

2

It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_values();

foreach ($values as $value){
  ...
}

When you feed a foreach with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in [...]

Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:

  • Casting $values to array
  • Initializing $values to array
  • Wrapping the foreach with an if
  • Other (please suggest)
+6  A: 

Personally I find this to be the most cleanest - not sure if it's the most efficient, mind!

if (is_array($values))
{
    foreach ($values as $value)
    {
        ...
    }
}

The reasons for my preference is so you're not allocating an empty array when you've got nothing to begin with anyway.

Andy Shellam
Or use count() to figure out if array isn't empty
Kemo
@Kemo: `count()` is not reliable. If you pass `count()` null, it returns 0. If you pass it a non-null, non-array argument, it returns 1. Therefore it's impossible to use `count()` to determine if the variable is an array when the variable could be an empty array, or an array containing 1 item.
Andy Shellam
A: 

First of all, every variable must be initialized. Always.
Casting is not an option.
if get_values(); can return different type variable, this value must be checked, of course.

Col. Shrapnel
Casting is an option - if you initialise an array using `$array = (array)null;` you get an empty array. Of course it's a waste of memory allocation ;-)
Andy Shellam