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?
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
    }
}
                        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 ? ',' : '');
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With