[php] How do I remove the last comma from a string using PHP?

I am using a loop to get values from my database and my result is like:

'name', 'name2', 'name3',

And I want it like this:

'name', 'name2', 'name3'

I want to remove the comma after the last value of the loop.

This question is related to php string substr

The answer is


Try:

$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');

Try the below code:

$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);

Use this code to remove the last character of the string.


Solutions to apply during a loop:

//1 - Using conditional:

$source = array (1,2,3);
$total = count($source);
    
$str = null;
    
for($i=0; $i <= $total; $i++){ 
        
    if($i < $total) {
        $str .= $i.',';
    }
    else {
        $str .= $i;
    }
}
    
echo $str; //0,1,2,3

//2 - Using rtrim:

$source = array (1,2,3);
$total = count($source);

$str = null;

for($i=0; $i <= $total; $i++){ 
    
        $str .= $i.',';
}

$str = substr($str,0,strlen($str)-1);
echo $str; //0,1,2,3

its as simple as:

$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');

You can use one of the following technique to remove the last comma(,)

Solution1:

$string = "'name', 'name2', 'name3',";  // this is the full string or text.
$string = chop($string,",");            // remove the last character (,) and store the updated value in $string variable.
echo $string;                           // to print update string.

Solution 2:

$string = '10,20,30,';              // this is the full string or text.
$string = rtrim($string,',');
echo $string;                       // to print update string.

Solution 3:

 $string = "'name', 'name2', 'name3',";  // this is the full string or text.
 $string = substr($string , 0, -1);
 echo $string;  

rtrim function

rtrim($my_string,',');

Second parameter indicates that comma to be deleted from right side.


You can use substr function to remove this.

$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);

It is better to use implode for that purpose. Implode is easy and awesome:

    $array = ['name1', 'name2', 'name3'];
    $str = implode(', ', $array);

Output:

    name1, name2, name3

use rtrim()

rtrim($string,',');

It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this ini_set("mbstring.func_overload", 2);

_x000D_
_x000D_
$string = "'test1', 'test2', 'test3',";_x000D_
echo mb_substr($string, 0, -1);
_x000D_
_x000D_
_x000D_