Hacker News new | ask | show | jobs
by wackget 2038 days 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); }

4 comments

For 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?

Since 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)

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.

While 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();
    }
You 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