Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent to Python's enumerate()?

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?

like image 808
davidscolgan Avatar asked Aug 24 '10 20:08

davidscolgan


People also ask

What is enumerate in for loop?

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.

Does enumerate work with lists?

The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary. In addition, it can also take in an optional argument, start, which specifies the number we want the count to start at (the default is 0). And that's it!

Can I enumerate a string in Python?

Yes you can, every item in the string is a character. This gives you the character index and the character value, for every character in the string. If you have a string you can iterate over it with enumerate(string). The code output above shows both the index and the value for every element of the string.

What does enumerate () do in Python?

Python enumerate() Function The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object. The enumerate() function adds a counter as the key of the enumerate object.


2 Answers

Don't trust PHP arrays, they are like Python dicts. If you want safe code consider this:

<?php
$lst = array('a', 'b', 'c');

// Removed a value to prove that keys are preserved
unset($lst[1]);

// So this wont work
foreach ($lst as $i => $val) {
        echo "$i $val \n";
}

echo "\n";

// Use array_values to reset the keys instead
foreach (array_values($lst) as $i => $val) {
        echo "$i $val \n";
}
?>

-

0 a 
2 c 

0 a 
1 c 
like image 119
Tomasz Wysocki Avatar answered Sep 22 '22 19:09

Tomasz Wysocki


Use foreach:

foreach ($lst as $i => $val) {
    echo $i, $val;
}
like image 39
Crozin Avatar answered Sep 25 '22 19:09

Crozin