Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

iterator_to_array

Turns an iterator or a generator into an array.

Syntax

iterator_to_array(iterable $iterator, bool $preserve_keys = true): array

Parameters

ParameterTypeDescription
$iteratoriterableAn iterator, a generator or an array.
$preserve_keysboolOptional. 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, 16

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.