views:

46

answers:

2

I have a lot of functions that either have type hinting for arrays or use is_array() to check the array-ness of a variable.

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

If I have to modify my code, is there a generic sort of is_iterable(), 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?

+1  A: 

Unfortunately you won't be able to use type hints for this and will have to do the is_array($var) or $var instanceof ArrayAccess stuff. This is a known issue but afaik it is still not resolved. At least it doesn't work with PHP 5.3.2 which I just tested.

Raoul Duke
+4  A: 

I think you mean insteanceof Iterator, PHP doesn't have an Iterable interface. It does have a Traversable interface though. Iterator and IteratorAggregate both implement extend Iterable (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);
}
NullUserException
`Iterator` and `IteratorAggregate` don't implement `Traversable`. They are interfaces and as such have no implementation. They *extend* `Traversable`. Other than that, +1
Artefacto