user151841 user151841 - 6 months ago 31
PHP Question

Iterable objects and array type hinting?

I have a lot of functions that either have type hinting for arrays or use

to check the array-ness of a variable.

Now I'm starting to use objects that are iterable. They implement
. Will these be accepted as arrays if they pass through type hinting, or undergo

If I have to modify my code, is there a generic sort of
, or must I do something like:

if ( is_array($var) OR $var instance_of Iterable OR $var instanceof IteratorAggregate ) { ... }

What other iterable interfaces are out there?


I think you mean instanceof Iterator, PHP doesn't have an Iterable interface. It does have a Traversable interface though. Iterator and IteratorAggregate both extend Traversable (and AFAIK they are the only ones to do so).

But no, objects implementing Traversable won't pass the is_array() check, nor there is a built-in is_iterable() function. A check you could use is

function is_iterable($var) {
    return (is_array($var) || $var instanceof Traversable);

To be clear, all php objects can be iterated with foreach, but only some of them implement Traversable. The presented is_iterable function will therefore not detect all things that foreach can handle.