How do I remove the last comma from a string using PHP?
PhpStringSubstrPhp Problem Overview
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.
Php Solutions
Solution 1 - Php
Use the rtrim
function:
rtrim($my_string, ',');
The Second parameter indicates the character to be deleted.
Solution 2 - Php
Try:
$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');
Solution 3 - Php
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.
Solution 4 - Php
You can use substr
function to remove this.
$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);
Solution 5 - Php
rtrim
function
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
Solution 6 - Php
use rtrim()
rtrim($string,',');
Solution 7 - Php
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
Solution 8 - Php
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);
$string = "'test1', 'test2', 'test3',";
echo mb_substr($string, 0, -1);
Solution 9 - Php
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;
Solution 10 - Php
its as simple as:
$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');
Solution 11 - Php
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