CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a PHP snippet (http://www.codingforums.com/forumdisplay.php?f=41)
-   -   while to foreach array (http://www.codingforums.com/showthread.php?t=174875)

seco 08-18-2009 08:37 PM

while to foreach array
 
Just a quick and simple snippet, im sure most of you know this one but for those who dont, enjoy.

PHP Code:

<?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 08: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 12:10 PM

Quote:

Originally Posted by abduraooft (Post 855184)
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

PHP Code:

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


seco 08-19-2009 12:47 PM

hmm, thanks!


All times are GMT +1. The time now is 06:13 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.