Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-18-2009, 08:37 PM   PM User | #1
seco
Regular Coder

 
seco's Avatar
 
Join Date: Nov 2008
Location: Oregon
Posts: 682
Thanks: 5
Thanked 79 Times in 77 Posts
seco has a little shameless behaviour in the past
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
seco is offline   Reply With Quote
Old 08-19-2009, 08:15 AM   PM User | #2
abduraooft
Supreme Master coder!

 
abduraooft's Avatar
 
Join Date: Mar 2007
Location: N/A
Posts: 14,680
Thanks: 158
Thanked 2,182 Times in 2,169 Posts
abduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really nice
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.
__________________
Quote:
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)
abduraooft is offline   Reply With Quote
Old 08-19-2009, 12:10 PM   PM User | #3
funnymoney
Regular Coder

 
funnymoney's Avatar
 
Join Date: Aug 2007
Posts: 364
Thanks: 17
Thanked 24 Times in 24 Posts
funnymoney is an unknown quantity at this point
Quote:
Originally Posted by abduraooft View Post
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++;
     } 
__________________
PHP Idea Factory
funnymoney is offline   Reply With Quote
Old 08-19-2009, 12:47 PM   PM User | #4
seco
Regular Coder

 
seco's Avatar
 
Join Date: Nov 2008
Location: Oregon
Posts: 682
Thanks: 5
Thanked 79 Times in 77 Posts
seco has a little shameless behaviour in the past
hmm, thanks!

Last edited by seco; 08-19-2009 at 12:53 PM..
seco is offline   Reply With Quote
Reply

Bookmarks

Tags
array, foreach, php, while loops

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:24 AM.


Advertisement
Log in to turn off these ads.