...

View Full Version : while to foreach array



seco
08-18-2009, 09:37 PM
Just a quick and simple snippet, im sure most of you know this one but for those who dont, enjoy.


<?php
while($row = mysql_fetch_array( $result )) {
$new=$row['fieldname'];
$new_array[] = $new;
}

foreach($new_array as $key => $value) {
echo $key. " - " . $value . "<br />";
}
?>

This will print out something similar to:

0 - result0
1 - result1
2 - result2
3 - result3
4 - result4

etc....
5 - result5

abduraooft
08-19-2009, 09:15 AM
But why do you need the second loop? You could use a counter variable, and increment it inside the first while loop to print the index.

funnymoney
08-19-2009, 01:10 PM
But why do you need the second loop? You could use a counter variable, and increment it inside the first while loop to print the index.

like this



$i=0;
while($row = mysql_fetch_array( $result )) {
echo $i. " - " . $row['fieldname'] . "<br />";
$i++;
}

seco
08-19-2009, 01:47 PM
hmm, thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum