SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2006
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    comma after each item in array except last

    As the title says, or of course it could be comma before each item except the first.

    I have a custom field that returns an array. That part works fine with
    PHP Code:
    <?php
    $values 
    get('recording_details_genre');
       foreach(
    $values as $value){
           
    printf('%s',$value);
           }
    ?>
    I have tried various ways to control adding a comma and space between each item so that I do not end up with a trailing comma. I am no PHP wiz. After a couple of dozen combinations I cam up with this, is there a better way?
    PHP Code:
    <?php
    $values 
    get('recording_details_genre');
    $count count($values);
    $i $count;
       foreach(
    $values as $value){
           
    $i $i -1;
           if (
    $i < ($count 1)) {
           
    printf(', %s',$value); }
           else{
         
    printf('%s',$value);
       }
      }       
    ?>

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)

  3. #3
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    With a comma space combo it sounds like you are trying to do something like this:
    PHP Code:
    $str "With my beer I like to eat ";
    $stuff = array('chips','tacos','burgers','kebabs');
    $last array_pop($stuff);
    $str .= join(', '$stuff) . " and $last.";
    echo 
    $str;

    // With my beer I like to eat chips, tacos, burgers and kebabs. 


Tags for this Thread

Bookmarks

Posting Permissions

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