Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

substr

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.

like image 710
JoJo Avatar asked Mar 14 '13 12:03

JoJo


People also ask

How do you remove the comma at the end of a string?

Using the substring() method We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string. length()-1 .

How can I remove last character from a string in PHP?

You can use the PHP rtrim() function to remove the last character from the given string in PHP.

How can I remove last 3 characters from a string in PHP?

To remove the last three characters from a string, we can use the substr() function by passing the start and length as arguments.

How do I remove the first and last character of a string in PHP?

Using trim : trim($dataList, '*'); This will remove all * characters (even if there are more than one!) from the end and the beginning of the string.


2 Answers

Use the rtrim function:

rtrim($my_string, ','); 

The Second parameter indicates the character to be deleted.

like image 176
Ander2 Avatar answered Sep 21 '22 10:09

Ander2


Try:

$string = "'name', 'name2', 'name3',"; $string = rtrim($string,','); 
like image 44
Boaz Avatar answered Sep 21 '22 10:09

Boaz