PHP equivalent to Python's enumerate()?

Viewed 10312

In Python I can write:

for i, val in enumerate(lst):
    print i, val

The only way I know how to do this in PHP is:

for($i = 0; $i < count(lst); $i++){
    echo "$i $val\n";
}

Is there a cleaner way in PHP?

8 Answers

I am using the helper function:

function enumerate(array &$array, callable $fn) {
    $i = 0;
    foreach ($array as $key => &$value)
        $fn($i++, $key, $value);
}

And I use it as follows:

enumerate($array, function ($i, $key, &$value) use (&$something)  {
    ...
});

The downside may be that you have to pass external variables that you want to use inside the loop through the use (...) directive.

Related