Zenexer
Zenexer

Reputation: 19611

Enumerate Iterator to array

So I have these Generator objects--you know, the cool new things in PHP 5.5 that make lazy enumeration easy. Sometimes, however, I don't want lazy enumeration: I want to take the data that I would normally iterate over and throw it all into an array--like LINQ has, but for PHP.

Most of the time I want a generator, but I still have a few times where I need an array. For example, if there is a possibility of enumerating the data multiple times, and a low chance of stopping the enumeration process before all items have been iterated over.

Is there some intrinsic PHP function that takes an Iterator or Traversable and outputs an array? What I really don't want to do is write my own function/method. Yes, I know, it'd be a short, simple procedure, but I like to avoid having a pile of helper functions scattered about.

Just to avoid the inevitable "use a foreach loop" answer, here's that approach:

<?php
function enumerate(\Traversable $iterator)
{
    $array = [];

    foreach ($iterator as $k => $v) {
        $array[$k] = $v;
    }

    return $array;
}

I have some other hackish ideas, but what I'm really looking for is a function that doesn't require any additional code, files, or libraries. Nothing fancy.

Upvotes: 1

Views: 401

Answers (1)

Itay
Itay

Reputation: 16785

Use iterator_to_array

iterator_to_array

(PHP 5 >= 5.1.0)

iterator_to_array — Copy the iterator into an array

Description

array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

Upvotes: 2

Related Questions