How to check if variable is array?... or something array-like

Voitcus picture Voitcus · Mar 24, 2013 · Viewed 132.3k times · Source

I want to use a foreach loop with a variable, but this variable can be many different types, NULL for example.

So before foreach I test it:

if(is_array($var)){
  foreach($var as ...

But I realized that it can also be a class that implements Iterator interface. Maybe I am blind but how to check whether the class implements interface? Is there something like is_a function or inherits operator? I found class_implements, I can use it, but maybe there is something simpler?

And second, more important, I suppose this function exist, would be enough to check if the variable is_array or "implements Iterator interface" or should I test for something more?

Answer

Shoe picture Shoe · Mar 24, 2013

If you are using foreach inside a function and you are expecting an array or a Traversable object you can type hint that function with:

function myFunction(array $a)
function myFunction(Traversable)

If you are not using foreach inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:

if (is_array($a) or ($a instanceof Traversable))