1

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.

1 Answer 1

2

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 ] )

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that's exactly what I was looking for! I knew I remembered seeing it somewhere, but it escaped quite a bit of Googling. Apparently I have to wait 8 minutes to mark this as the answer, though.
@Zenexer Found it by googling php iterator into array
I think I was focusing too much on generator in my searches. Got too much unrelated stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.