PHP Reference ยท Types and Type Handling
The PHP iterable type
Reference for the PHP iterable pseudo-type: what it accepts, is_iterable(), iterating generators and iterators, and how it relates to Traversable.
iterable is a type declaration meaning "something you can loop over with foreach". It accepts either an array or any object that implements Traversable, which includes generators, Iterator and IteratorAggregate implementations and classes such as ArrayObject.
Use it when a function only needs to loop over its input once and does not care whether the data sits in memory in an array or is produced lazily. It was added in PHP 7.1. Since PHP 8.2 it is simply an alias for the union array|Traversable.
function total(iterable $numbers): int { $sum = 0; foreach ($numbers as $n) { $sum += $n; } return $sum; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
function process(iterable $items): void { /* ... */ } function make(): iterable { yield 1; } is_iterable($value): bool iterator_to_array(Traversable $it, bool $preserve_keys = true): array
| Value | Accepted by iterable? |
|---|---|
array |
yes |
Generator, Iterator, IteratorAggregate, ArrayObject |
yes |
Plain stdClass or other object without Traversable |
no |
string, int, null |
no |
Usage notes
- A generator can be traversed only once. If you loop over it a second time you get an exception ("Cannot traverse an already closed generator"). Convert it to an array first if you need several passes.
- Do not call array functions on an
iterable.array_map()andcount()need arrays (count()also acceptsCountable). Useiterator_to_array(),iterator_count()or write aforeach. - Duplicate keys.
iterator_to_array()keeps the last value for repeated keys when it preserves keys (see the second example); passfalseto get a list. - Return type
iterablelets an implementation return an array now and switch to a generator later without breaking callers, but callers can only useforeachon the result. - Narrowing subclasses: a child method may declare the narrower
arrayorTraversablereturn type; parameters may widen toiterable. iterablecannot be used as a class name and does not combine witharrayorTraversablein a union (it would be redundant, so PHP rejects it).- Large data. Streaming a file or a database result through a generator with an
iterableparameter keeps memory flat. See Generators.