views:

67

answers:

3

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?

+9  A: 

Use foreach:

foreach ($lst as $i => $val) {
    echo $i, $val;
}
Crozin
Only works if the array is not associative and/or the keys are continuous.
Felix Kling
@Felix Kling: Huh? `foreach` works for all `Traversable` objects and arrays. What are you referring to?
ircmaxell
@ircmaxell: Python's `enumerate()` counts from a start value (default `0`) to `#listElements`. You on the other hand are just outputting the keys of the array. If the array is associative, then it is not equivalent to the `enumerate()` function. See Tomasz answer.
Felix Kling
+1  A: 

Yes, you can use foreach loop of PHP:

 foreach($lst as $i => $val)
       echo $i.$val;
shamittomar
+5  A: 

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

<?php
$lst = array('a', 'b', 'c');
unset($lst[1]);
foreach ($lst as $i => $val) {
        echo "$i $val \n";
}
foreach (array_values($lst) as $i => $val) {
        echo "$i $val \n";
}
?>

-

0 a 
2 c 
0 a 
1 c 
Tomasz Wysocki
+1: the second example using `array_values` is basically what `enumerate` does (of course `enumerate` also accepts iterators, so you'd need a bit more code to handle that case)...
ircmaxell