38

Possible Duplicate:
Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

Martijn
  • 15,791
  • 4
  • 36
  • 68
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
  • 2
    Possible Duplicate of [find last character in a string in php](http://stackoverflow.com/questions/4427172/find-last-character-in-a-string-in-php). Won't tell you if the string starts with a comma, but I take you know how to use an `if`. – Gordon Jan 21 '11 at 23:22
  • 2
    [PHP Manual: string functions](http://php.net/manual/en/ref.strings.php) – Pekka Jan 21 '11 at 23:22
  • While not an answer, probably the most common reason someone would ask this question is that they want to know if there is a comma they should remove; or perhaps whether they should add or a comma, or one already exists. For these cases, something like `$string = rtrim($string, ',')` is probably the simplest path: you don't NEED to know whether there's something on the end, then. – Dewi Morgan Mar 30 '18 at 15:59
  • 1
    PHP 8.0 introduces new method for this job `str_end_with`: https://stackoverflow.com/a/64160081/7082164 – Jsowa Oct 01 '20 at 17:05

7 Answers7

125

There are a few options:

if (substr($string, -1) == ',') {

Or (slightly less readable):

if ($string[strlen($string) - 1] == ',') {

Or (even less readable):

if (strrpos($string, ',') == strlen($string) - 1) {

Or (even worse yet):

if (preg_match('/,$/', $string)) {

Or (wow this is bad):

if (end(explode(',', $string)) == '') {

The take away, is just use substr($string, -1) and be done with it. But there are many other alternatives out there...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
12
$string = 'foo,bar,';
if(substr($string, -1) === ','){
    // it ends with ','
}
Floern
  • 33,559
  • 24
  • 104
  • 119
6

You can use regular expressions for this in PHP:

if (preg_match("/,$/", $string)) {
    #DO THIS
} else {
    #DO THAT
}

This says to check for a match of a comma at the end of the $string.

4
if (substr($str, -1) === ',') 
{
 echo 'it is';
}
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
3

For the micro optimizers:

$string[strlen($string)-1] == ","
mario
  • 144,265
  • 20
  • 237
  • 291
2

See the endsWith function here:

startsWith() and endsWith() functions in PHP

Community
  • 1
  • 1
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
2
//$str hold your string
if(substr($str, -1) ==',')
{
   return true
}
slier
  • 6,511
  • 6
  • 36
  • 55