Php for each comma separated last

I am working on using jplayer html5 audio playlist

I use foreach to create a script item for each playlist item. Everything works as expected, except that I included the comma in the loop, but I need a way to write the comma as a separator, with the exception of the last element.

here is what i have to create a 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 someone point me in the right direction?

+5
source share
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
    }
}
+11
source

Do you mean JSON?

echo json_encode($array);

You can also use array functions

// 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);

, : 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 ? ',' : '');
}
+4

, , , , .

<?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;
 ?>

, .

+2

All Articles