Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterable objects and array type hinting?

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?

like image 287
user151841 Avatar asked Aug 27 '10 13:08

user151841


People also ask

What is iterable in typescript?

Iterables. An object is deemed iterable if it has an implementation for the Symbol. iterator property. Some built-in types like Array , Map , Set , String , Int32Array , Uint32Array , etc. have their Symbol.

Are arrays iterable?

Iterable objects are a generalization of arrays. That's a concept that allows us to make any object useable in a for..of loop. Of course, Arrays are iterable.

How many types of arrays are there in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

Is array an object PHP?

An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array. An array which contains string index is called associative array.


1 Answers

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.

like image 65
NullUserException Avatar answered Sep 23 '22 06:09

NullUserException