Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php for each with comma separator except last

Tags:

php

I am working on incorperating the jplayer html5 audio playlist

I'm using a foreach to generate the script element for each playlist item. Everything is working as expected, Except I've included the comma in the loop, but I need a way to write the comma as separator except for last item.

here is what I've got so far to generate jplayer playlist.

<?php foreach( $songs as $song ): if( !empty($song) ): ?>{

        title:"Each Song Title",

        mp3:"Each song mp3 url"

    },<?php endif; endforeach; ?>

which gives me

    {

        title:"Partir",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-09-Partir.mp3"

    },

    {

        title:"Thin Ice",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-10-Thin-ice.mp3"

    },
    {

        title:"Ice man",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-10-Thin-ice.mp3"

    },

This is my desired result

    {

        title:"Partir",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-09-Partir.mp3"

    },

    {

        title:"Thin Ice",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-10-Thin-ice.mp3"

    },
    {

        title:"Ice man",

        mp3:"http://www.jplayer.org/audio/mp3/Miaow-10-Thin-ice.mp3"

    }

Can anyone point me in the right direction?

like image 513
Mike M Avatar asked Jul 06 '12 06:07

Mike M


3 Answers

I use next() for it:

$arr = array(1,2,3,4,5,6,7);
$copy = $arr;
foreach ($arr as $val) {
    echo $val;
    if (next($copy )) {
        echo ','; // Add comma for all elements instead of last
    }
}
like image 166
Alex Pliutau Avatar answered Nov 02 '22 08:11

Alex Pliutau


You mean JSON?

echo json_encode($array);

Also you can use array functions instead

// Create single items first
$array = array_map(
  function ($item) {return sprintf(
      '{title:"%s",mp3:"%s"}',
      $item['title'],
      $item['mp3']
  );},
  $array
);
// Then concatenate
echo implode(',' $array);

Just to make it complete: A for-solution

for ($n = count($array), $i = 0; $i < $n; $i++) {
  echo sprintf('{title:"%s",mp3:"%s"}', $array[$i]['title'], $array[$i]['mp3'])
    . ($i < $n-1 ? ',' : '');
}
like image 29
KingCrunch Avatar answered Nov 02 '22 07:11

KingCrunch


What you can also do, is rather than echo it directly to the browser, store it in a string first.

<?php 
$string = "";
foreach( $songs as $song ) { 
    if( !empty($song) )
    { 
        $string .= '
    {

        title:"Each Song Title",

        mp3:"Each song mp3 url"

    },

    ';
    }
 }
 $string = substr($string, 0, -1); //Removes very last comma.
 echo $string;
 ?>

This also allows it to be used elsewhere throughout your code, if needed.

like image 4
Connor Deckers Avatar answered Nov 02 '22 07:11

Connor Deckers