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?
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
)
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With