Forum Moderators: coopster

Message Too Old, No Replies

foreach loop count

         

pixelhub

4:15 pm on Mar 24, 2009 (gmt 0)

10+ Year Member


Hi,

I am trying to show the count of each row in the loop
so it looks like this

1 one
2 two
3 three

I know how to count the values in the array but i can't get the row number next to the value when using a foreach loop.

[code]

<php
$arr = array("one", "two", "three");

$count = count($arr); // 3
for ($i=1; $i<=$count; $i++) {
echo $i; // 1 2 3
}

foreach ($arr as $value) {
echo $value . "<br />\n";
}
?>

[/code]

Thanks

d40sithui

4:29 pm on Mar 24, 2009 (gmt 0)

10+ Year Member



Both methods work

for($i = 0; $i < sizeof($arr); $i++){
echo "$i ".$arr[$i]."<br>";
}

foreach(array_keys($arr) as $key){
echo $key ." ". $arr[$key]."<br>";
}

pixelhub

5:10 pm on Mar 24, 2009 (gmt 0)

10+ Year Member



Thanks for the quick reply, the array_keys function works a treat :)

Thanks again