3 ms·
Where's the best place to suggest a new feature or improvement for PHP? I've always wanted to see `foreach` get a built-in iterator/counter so you don't have t
by wackget 6y ago
Where's the best place to suggest a new feature or improvement for PHP?
I've always wanted to see `foreach` get a built-in iterator/counter so you don't have to create and use a counter variable manually.
Current way:
$i=0;
foreach ($array as $key => $value) {
echo "Loop $i of " . count($array);
$i++;
}
Possible new way:
foreach ($array as $key => $value, $i) {
echo "Loop $i of " . count($array);
}
- deleted 6y ago[deleted]
- throw_m239339 6y agohttps://wiki.php.net/rfc https://wiki.php.net/rfc IMHO that array/map data structure is one of PHP's biggest sin. So many bugs as the result of it and it makes a lot of codebases barely readable.
- mdaniel 6y agoFor that code snippet specifically, you're actually better off pre-declaring the vars since the loop repeatedly calls `count($array)` but hopefully(!) its size doesn't change over time. Is there such a function in php like "enumerate" in python, that yields a tuple of (counter, item) for each item in the first argument to enumerate? That is to say: is it possible to do what you're asking with composition rather than a language change?
- johannes1234321 6y agoSince count is it's own opcodes in the VM and php hashtables keep the number of elements around and don't have to be counted there shouldn't be much difference between reading a variable and calling count. (Since some time in PHP 7, before that count() went via function call overhead)
- kingdomcome50 6y agoWhile not quite as ergonomic as your example, it's rather trivial to extend ArrayIterator to accomplish your goal: foreach ($iter = new IndexingIterator($array) as $k => $v) { echo $iter->index(); }
- tpetry 6y agoYou can do it very simple by writing a custom generator function: foreach(myfunc($array) as list($key, $value, $loop)) {} Maybe you can array destructuring at this place, i am not sure at the moment. And your manual counting you do in myfunc() and just yield the values