Search code examples
phparraysstringtrim

How to remove last character (comma when creating a string from an array)?


I am trying to remove last character in the output of this code:

$images = "image1,image2,image3";
$images = explode(',', $images);

foreach ($images as $image) {
    echo "'$image',";
}}

current output:

'image1','image2','image3',
                        //^ See here

expected output:

'image1','image2','image3'
                        //^ See here

Solution

  • Just keep it simple and use implode(), e.g.

    <?php
    
        $images = "image1,image2,image3";
        $arr = explode(",", $images);
        echo "'" . implode("','", $arr) . "'";
    
    ?>
    

    output:

    'image1','image2','image3'