iterator_to_array
Turns an iterator or a generator into an array.
Syntax
iterator_to_array(iterable $iterator, bool $preserve_keys = true): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $iterator | iterable | An iterator, a generator or an array. |
| $preserve_keys | bool | Optional. Whether to keep the keys. |
Return value
arrayAn array with all the elements.
Examples
A generator into an array:
<?php
function squares(int $limit): Generator
{
for ($i = 1; $i <= $limit; $i++) {
yield $i * $i;
}
}
echo implode(', ', iterator_to_array(squares(4)));Output:
1, 4, 9, 16Notes
If a generator yields repeated keys, later values overwrite earlier ones — pass false as the second argument.
See also
- array_values — Returns the values of an array with keys numbered from zero.
- array_map — Applies a function to every element of an array.
- range — Creates an array holding a sequence of values.
Related recipes
In the tutorial
- Built-in interfaces — PHP interfaces that teach an object to behave like an array — Countable, IteratorAggregate, ArrayAccess, JsonSerializable and Stringable.