Keiran Lovett
Keiran Lovett

Reputation: 604

PHP - Edit last row in foreach

I have the following code to create a music playlist based on files in a folder. The issue is that the foreach section will echo the comma of the last row. Here is the code below:

echo '<script type="text/javascript">
                $(document).ready(function(){
                    new jPlayerPlaylist({
                        jPlayer: "#jquery_jplayer_'. $counter .'",
                        cssSelectorAncestor: "#jp_container_'. $counter .'"
                    }, [';

            foreach(glob('files/'. $dir .'/*.mp3') as $file) {
                $filename = $file;
                $parts = Explode('/', $filename);
                $filename = $parts[count($parts) - 1];
                echo '{';
                echo 'title:"'. $filename .'",';
                echo 'mp3:"'.$file.'",';
                echo '},';
            } 
            echo'
                ], {
                    swfPath: "js",
                    supplied: "oga, mp3",
                    wmode: "window"
                    });
                });
            </script>'; 
            $counter ++;
    } 

with the line with the comma being line 15 here:

            echo '},';

Does anyone know of a simple solution to this. I've been racking my head trying to find out all day that nothings making sense anymore. CHEERS!

Upvotes: 0

Views: 179

Answers (2)

quider
quider

Reputation: 1

If I understood correctly what you wanna do: Try to make your loop with iterator, then you will be able to check if there is next object to iterate.

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60584

Get the files before loop, and the count of it, then check on every iteration

$files = glob('files/'. $dir .'/*.mp3');
$fCnt = count($files);
foreach($files as $i => $file) {
   -- SNIP --
   echo '}' . ($i != $fCnt - 1 ? ',' : '');
}

Upvotes: 1

Related Questions