←back to thread

116 points doekenorg | 2 comments | | HN request time: 0.001s | source
Show context
Amakanski ◴[] No.44498559[source]
>> This would require a yield to syntax, which doesn't exist.

There is however the 'yield from' statement.

replies(3): >>44498922 #>>44499113 #>>44499996 #
Cyykratahk ◴[] No.44499113[source]
I'd use `yield from` more if I didn't have to re-index arrays before yielding from them:

    function numbers() {
      yield from [1,2,3];
      yield from [4,5,6];
    };
    
    foreach (numbers() as $k => $v) { echo "$k => $v\n"; }
    0 => 1
    1 => 2
    2 => 3
    0 => 4
    1 => 5
    2 => 6
replies(1): >>44499518 #
bvrmn ◴[] No.44499518[source]
PHP generators/iterators is a hot mess. I don't know any other language which forces iterators to output a key for `foreach(... as $key => ...)`.
replies(2): >>44499619 #>>44512570 #
jw1224 ◴[] No.44499619[source]
PHP doesn’t force keys... You can omit the key and simply write `foreach($items as $value)`
replies(2): >>44503392 #>>44503403 #
1. bvrmn ◴[] No.44503392[source]
What's idiomatic way to get index (0, n-1) with the value? Parent example shows you could not use $key as a generic solution.
replies(1): >>44509486 #
2. doekenorg ◴[] No.44509486[source]
You can use the SPL LimitIterator, feed it the generator, and give it the offset and limit.

``` foreach (new LimitIterator($generator, 0, 3) as $value) { echo $value; } ```

https://www.php.net/manual/en/class.limititerator.php