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?
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?
Yes, you can use foreach
loop of PHP:
foreach($lst as $i => $val)
echo $i.$val;
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