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.
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.
You may use the rtrim
function. The following code will remove all trailing commas:
rtrim($my_string, ',');
The Second parameter indicates characters to be deleted.
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.
You can use substr
function to remove this.
$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);
rtrim
function
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
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
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);
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;
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
I tried everithing and just this solve my problem
$string = '10,20,30,'; // this is the full string or text.
$string = trim(trim($string),','); //double trim function
echo $string; // to print update string.