Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

iterator_to_array()

Materialize the traversal in an array.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

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

Materialize the traversal in an array. Keys are preserved by default and a later duplicate overwrites the earlier value. Pass false to append every yielded value under a fresh integer index. Since PHP 8.2 the input can also be an array.

Signature

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

Example output

[{"id":"second"},["first","second"]]

Examples

<?php
function labels(): Generator { yield "id"=>"first"; yield "id"=>"second"; }
echo json_encode([iterator_to_array(labels()),iterator_to_array(labels(),false)]);

Result

[{"id":"second"},["first","second"]]

Sources