Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implode a generator?

Tags:

generator

php

I have a PHP generator which generates some $key => $value.

Is there an "easy" way to implode the values (by passing the generator name)? Or to transform it to an array?

I can do this with a couple of lines of code, but are there some builtins functions to accomplish this?

like image 697
oliverpool Avatar asked Apr 07 '16 08:04

oliverpool


2 Answers

You can use iterator_to_array function for the same, have a look on below example:

function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();

$array = iterator_to_array($generator);
print_r($array);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
like image 138
Chetan Ameta Avatar answered Nov 14 '22 23:11

Chetan Ameta


One has to keep in mind that

A generator is simply a function that returns an iterator.

For instance:

function digits() {
    for ($i = 0; $i < 10; $i++) {
        yield $i;
    }
}

digits is a generator, digits() is an iterator.

Hence one should search for "iterator to array" functions, to find iterator_to_array (suggested by Chetan Ameta )

like image 30
oliverpool Avatar answered Nov 14 '22 22:11

oliverpool