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?
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.
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!
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.
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.
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
Use foreach
:
foreach ($lst as $i => $val) {
echo $i, $val;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With