Search code examples
phpexplode

PHP explode keywords but dont echo comma on the end


I need a list of keywords to split on 'keyword' but how to dont print the comma on the end, i know to count tags and to check if last tag and to dont display but im interesting in any other clean and good way.

Im using in this way:

$keywords = 'keyword1 keyword2 keyword3';
$keywords = explode(" ", $keywords);
foreach ($keywords as $keyword) {
echo "'" . $keyword . "', ";
}

this is printing:

'keyword1', 'keyword2', 'keyword3',

but i like to print without comma in the end, in this way:

'keyword1', 'keyword2', 'keyword3'

Solution

  • You could use implode:
    You can try something like:

    <?php
    $keywords = 'keyword1 keyword2 keyword3';
    $keywords = explode(" ", $keywords);
    echo "'". implode("', '", $keywords) . "'";