Skip to main content
iterable is a built-in pseudo-type in PHP, introduced in version 7.1, that acts as a strict type alias for the union array|Traversable. While plain objects (such as stdClass or user-defined classes) can be iterated over using a foreach loop to access visible properties, they do not satisfy the iterable type constraint. A value is only considered iterable if it is a primitive array or an object that explicitly implements the Traversable interface. Because Traversable is an internal engine interface that cannot be implemented directly in userland PHP, an object satisfies the iterable pseudo-type if it implements either the Iterator or IteratorAggregate interfaces.

Type Declarations

iterable can be used as a parameter type, a return type, and (as of PHP 7.4) a class property type. Parameter Type:
Return Type:
Property Type:

Runtime Type Checking

PHP provides the is_iterable() function to verify at runtime whether a variable’s contents satisfy the iterable pseudo-type constraints.

Generators and Iterable

Generator functions, which utilize the yield keyword, return a Generator object. Because the Generator class implements the Iterator interface, generator return values inherently satisfy the iterable type declaration.

Variance Rules in Inheritance

When extending classes or implementing interfaces, iterable adheres to PHP’s standard rules for type variance. Covariance (Return Types): A child class can narrow a return type from iterable to a more specific type, such as array or a specific class implementing Traversable.
Contravariance (Parameter Types): A child class can widen a parameter type from array or a specific Traversable implementation to the broader iterable pseudo-type.

Default Values

When used as a parameter type, iterable allows for default values. This can be an array, null (if the type is nullable), or, as of PHP 8.1, an instantiated Traversable object utilizing new expressions in initializers.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More