5 ms·
PHP doesn’t force keys... You can omit the key and simply write `foreach($items as $value)`
by jw1224 1y ago
PHP doesn’t force keys... You can omit the key and simply write `foreach($items as $value)`
- bvrmn 1y agoBTW: https://www.php.net/manual/en/iterator.key.php https://www.php.net/manual/en/iterator.key.php It's literally in the interface.
- jw1224 1y agoI’m not sure I follow, what exactly is your complaint? The Iterator interface is described as: > Interface for external iterators or objects that can be iterated themselves internally Note “external iterators or objects”. The Iterator interface is not exactly everyday PHP, it’s a specialist utility for making classes iterable so they can be accessed like arrays. Most developers will rarely use it directly, and it’s not being used in the parent comment’s example either. Iterating over something requires knowing where you are in the sequence, so of course you would need to implement a method to get the current position of the iteration.
- bvrmn 1y ago> Iterating over something requires knowing where you are in the sequence, so of course you would need to implement a method to get the current position of the iteration. No you don't. Other languages don't require it. There is no issue to get a position outside of iterator and it's more generic approach.
- jw1224 1y agoI don’t think you understand the purpose of PHP’s Iterator interface.
- bvrmn 1y agoLet me guess. To somehow patch iteration on associative arrays? And instead of bringing pairs or tuples as first class citizens it extends iterators with `key` and `value`. And now any Iterator implementation should track own sequentially increasing key. Very nice design indeed.
- jw1224 1y agoAssociative arrays are iterable internally without needing an interface or key tracking. You can just foreach them. > Let me guess. This just proves my point, you call this a “hot mess” whilst completely misunderstanding what it’s even used for. The Iterator interface isn’t even used in the comment you first replied to.
- bvrmn 1y agoWhat's idiomatic way to get index (0, n-1) with the value? Parent example shows you could not use $key as a generic solution.
- doekenorg 1y agoYou 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 https://www.php.net/manual/en/class.limititerator.php