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 3 of 3
  1. #1
    New Coder
    Join Date
    Mar 2012
    Location
    Ontario, Canada
    Posts
    51
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Displaying Array Values

    I am having a hard time displaying an array values once. when I loop through the first value repeats itself. how do I display the array values in a single row.

    I should see the following:

    English, Spanish

    Code:
    while($t = mysql_fetch_array($genres)) {
         $gens[] = $t['gen_name'];				   
         foreach ($gens as $msg) {					
               $v .= $msg . ", ";						
         }
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    This is due to you adding to an array. Since $gens[] is appending on each iteration of $genres, and then within each iteration of $genres it iterates $gens, it will just grow as each record goes through. Lets say you have three records of $genres, 'pop', 'rock', 'jazz' in that order. The iterations of the while would leave the $v in the following states:
    1. pop,
    2. pop, pop, rock
    3. pop, pop, rock, pop, rock, jazz,


    So if I had to guess what you are looking for, it is this:
    PHP Code:
    while ($t mysql_fetch_assoc($genres))
    {
        
    $gens[] = $t['gen_name'];
    }
    $v implode(', '$gens);

    // or

    $i 0;
    $v '';
    while (
    $t mysql_fetch_assoc($genres))
    {
        if (
    $i++ > 0)
        {
            
    $v .= ', ';
        }
        
    $v .= $t['gen_name'];

    Both of which should result in $v being 'pop, rock, jazz' if I didn't biff it.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    chellert (02-07-2013)

  • #3
    New Coder
    Join Date
    Mar 2012
    Location
    Ontario, Canada
    Posts
    51
    Thanks
    9
    Thanked 0 Times in 0 Posts
    thank you again for all of your help


  •  

    Posting Permissions

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