Question about php foreach

Discussion in 'PHP' started by levani, Aug 2, 2009.

  1. #1
    <?php
    $post_ids = $wpdb->get_col("SELECT comment_post_ID FROM $wpdb->comments WHERE user_id = $current_user->ID AND comment_approved = '1' ");
    foreach($post_ids as $post_id) {
    $shedeg .= "$post_id, ";
    }
    echo $shedeg;
    ?>
    PHP:
    As you see this code adds , symbol to every $post_id value. How can I prevent adding it to the last value only.

    Now the result is:
    1, 2, 3, 4, 5,

    And I need it to be:

    1, 2, 3, 4, 5

    Thanks in advance
     
    levani, Aug 2, 2009 IP
  2. linkinpark2014

    linkinpark2014 Peon

    Messages:
    153
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    <?php
    $post_ids = $wpdb->get_col("SELECT comment_post_ID FROM $wpdb->comments WHERE user_id = $current_user->ID AND comment_approved = '1' ");
    foreach($post_ids as $post_id) {
    $shedeg .= "$post_id, ";
    }
    $shedeg = substr($shedeg, 0, -1);
    echo $shedeg;
    ?>

    add new line (bolded)
    rep me up :D
     
    linkinpark2014, Aug 2, 2009 IP
  3. keaglez

    keaglez Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or use trim, for example:
    
    $shedeg = trim($shedeg, ",");
    
    PHP:
     
    keaglez, Aug 2, 2009 IP
  4. stOK

    stOK Active Member

    Messages:
    114
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #4
    I would do that like this
    <?php
    $post_ids = $wpdb->get_col("SELECT comment_post_ID FROM $wpdb->comments WHERE user_id = $current_user->ID AND comment_approved = '1' ");
    $shedeg='';
    foreach($post_ids as $post_id) {
    $shedeg .= (('' === $shedeg)?', ':'').$post_id;
    }
    echo $shedeg;
    ?>
    
    PHP:
    PS
    I believe $shedeg = trim($shedeg, ",");
    won't work since the last char is ' ' (space) not comma.
     
    stOK, Aug 2, 2009 IP
  5. keaglez

    keaglez Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Oh, thanks to point out that... :) it should be this then
    $shedeg = trim($shedeg, ", ");
    PHP:
     
    keaglez, Aug 2, 2009 IP
  6. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Guys, there's a function specific to this:

    
    $shedeg = implode(',', $shedeg); 
    
    Code (markup):
    There, no need to complicate matters :)
     
    premiumscripts, Aug 3, 2009 IP