Advertisement
Google Ad Slot: content-top
PHP Iterables
PHP - What is an Iterable?
An iterable is any value that can be looped through with a foreach loop.
In PHP, an iterable can be:
- An array
- An object that implements the
Traversableinterface (like generators or iterators)
The iterable pseudo-type was introduced in PHP 7.1.
PHP - Using Iterables
The iterablepseudo-type can be used in function arguments and return types to indicate that the value must be something you can iterate over using foreach.
You can also return an iterable:
PHP - Creating Iterables
1. Arrays Are Iterables
All arrays in PHP are inherently iterable and can be passed to functions expecting an iterable type.
2. Iterators Are Also Iterables
Any object that implements the Iterator interface is considered iterable. This allows for custom iteration logic.
The Required Methods of the Iterator Interface
To be a valid iterator in PHP, your class must implement:
Method |
Purpose |
|---|---|
current() |
Returns the value of the current item |
key() |
Returns the key of the current item (int, float, bool, or string) |
next() |
Moves the pointer to the next item |
rewind() |
Resets the pointer to the first item |
valid() |
Returns |