How do I place commas between results?

Discussion in 'PHP' started by wwwbryan, Apr 24, 2009.

  1. #1
    I have a query that gets a list of online members from the database.

    
    <?php
    $main .=  '<div class="t1">
    ';
    while( $activeArray=mysql_fetch_array($activeQuery) )
    {
        $main .=  '<a href="./index.php?member=' . $activeArray['mid'] . '">' . $activeArray['username'] . '</a> (' . $activeArray['location'] . ') ';
    }$main .= '
    </div>
    ';
    ?>
    PHP:
    How do I make that part which displays the results separate each user with a comma but not put a comma after the last result?
     
    wwwbryan, Apr 24, 2009 IP
  2. Nitroshock

    Nitroshock Peon

    Messages:
    76
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    My php is rusty but you'll most likely want to use the join() function. It joins elements in an array into a single string with each item separated by whatever is in the quotes.

    Something like this:
     join(", ", $array) 
    Code (markup):
     
    Nitroshock, Apr 24, 2009 IP
  3. wwwbryan

    wwwbryan Well-Known Member

    Messages:
    181
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    103
    #3
    It works good for arrays, but I have no idea how to make that work for a query.
     
    wwwbryan, Apr 24, 2009 IP
  4. decepti0n

    decepti0n Peon

    Messages:
    519
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    0
    #4
    <?php
    
    $elements = array();
    
    while( $activeArray=mysql_fetch_array($activeQuery) )
    {
        $elements[] =  '<a href="./index.php?member=' . $activeArray['mid'] . '">' . $activeArray['username'] . '</a> (' . $activeArray['location'] . ') ';
    }
    
    $main =  '<div class="t1">' . implode(', ', $elements) . '</div>';
    ?>
    PHP:
     
    decepti0n, Apr 25, 2009 IP
  5. wwwbryan

    wwwbryan Well-Known Member

    Messages:
    181
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    103
    #5
    Thank you you made my day today. Works like a charm.
     
    wwwbryan, Apr 25, 2009 IP