Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder seco's Avatar
    Join Date
    Nov 2008
    Location
    Oregon
    Posts
    687
    Thanks
    6
    Thanked 79 Times in 77 Posts

    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

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,863
    Thanks
    160
    Thanked 2,224 Times in 2,211 Posts
    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.
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    Regular Coder funnymoney's Avatar
    Join Date
    Aug 2007
    Posts
    364
    Thanks
    17
    Thanked 24 Times in 24 Posts
    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++;
         } 

  • #4
    Regular Coder seco's Avatar
    Join Date
    Nov 2008
    Location
    Oregon
    Posts
    687
    Thanks
    6
    Thanked 79 Times in 77 Posts
    hmm, thanks!
    Last edited by seco; 08-19-2009 at 01:53 PM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •