568

I need to get the last character of a string. Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?

Cœur
  • 37,241
  • 25
  • 195
  • 267
streetparade
  • 32,000
  • 37
  • 101
  • 123
  • You might find [`s($str)->end()`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L192) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). – caw Jul 26 '16 at 23:43

13 Answers13

1196
substr("testers", -1); // returns "s"

Or, for multibyte strings :

mb_substr("multibyte string…", -1); // returns "…"
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Rich Adams
  • 26,096
  • 4
  • 39
  • 62
  • 131
    If you’re using multibyte character encodings like UTF-8, use `mb_substr` (http://php.net/mb_substr) instead. – Gumbo Apr 21 '10 at 10:19
  • 12
    so much for my substr($string, strlen($string)-1, 1);. Seems I've taken the LONG way around! – jeffkee Mar 19 '14 at 22:58
  • 6
    You only need multibyte string functions if the string is evaluated as binary string. Aka, when php doesn't know the encoding. Otherwise the typical non multibyte string functions will work just fine. – Ray Foss Mar 16 '15 at 17:50
  • Please see Yes Barry's answer. From PHP 8 you can use `str_ends_with()` – Tim Rogers May 08 '23 at 17:40
95
substr($string, -1) 
knittl
  • 246,190
  • 53
  • 318
  • 364
79

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

Gordon
  • 312,688
  • 75
  • 539
  • 559
55

From PHP 7.1 you can do this (Accepted rfc for negative string offsets):

<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();

I'll let you guess the output.

Also, I added this to xenonite's performance code with these results:

substr() took 7.0334868431091seconds

array access took 2.3111131191254seconds

Direct string access (negative string offsets) took 1.7971360683441seconds

RyanNerd
  • 3,059
  • 1
  • 22
  • 28
  • Thanks for posting benchmarks! If anyone is interested in C# benchmarks for doing the same thing, [this page](http://cc.davelozinski.com/c-sharp/c-fastest-way-to-check-last-character-of-a-string) is a good read. Directly accessing the last character won out. –  Jun 07 '17 at 01:28
  • could you explain more about difference between [] and {} in this context? – Taufik Nur Rahmanda Oct 16 '18 at 06:49
  • 2
    @TaufikNurRahmanda Technically there is no difference between [] and {}. The PHP developers gave the option to use either. For more details see: http://php.net/manual/en/migration71.new-features.php – RyanNerd Oct 24 '18 at 08:50
  • what is array access and what is direct string access? @RyanNerd afaik those are 2 same things, no? – CT. Jul 25 '19 at 12:51
  • @CT. See Xenonite's answer and benchmarks above. I am using his language for the description of each string access method. – RyanNerd Jul 26 '19 at 12:46
  • 1
    $string{1} will be deprecated in PHP 7.4 (RFC: https://wiki.php.net/rfc/deprecate_curly_braces_array_access) – Tony Vlcek Oct 07 '19 at 20:43
  • You missed an `i` out ;) – Jake Feb 20 '21 at 22:43
  • 1
    It spells `readablilty`. I assume he meant `readability`? Yes, 5 years later, I was curious lol. – Wade Jul 17 '21 at 05:20
  • 1
    IMPORTANT: when the string is empty, it will thow an error `PHP Notice: Uninitialized string offset: -1`. So, check that before. – sdlins Sep 06 '21 at 17:57
35

As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this:

$str[-1]

DEMO

At the request of a @mickmackusa, I supplement my answer with possible ways of application:

<?php

$str='abcdef';
var_dump($str[-2]); // => string(1) "e"

$str[-3]='.';
var_dump($str);     // => string(6) "abc.ef"

var_dump(isset($str[-4]));  // => bool(true)

var_dump(isset($str[-10])); // => bool(false)
nektobit
  • 843
  • 7
  • 11
  • Using negative offsets was a technique mentioned years earlier by RyanNerd. Please post an answer only when you have unique and valuable insights to share. – mickmackusa Mar 25 '20 at 10:05
  • 1
    @mickmackusa Why did you write it only to me and ignored the multiple variations substr()? – nektobit Mar 25 '20 at 23:35
  • 1
    Nothing personal, I just saw your very short and redundant answer and decided to blow my whistle. Feel free to whistleblow the other answers if you feel they add no value. Keep in mind, two answers can suggest the same technique but both be individually valuable because of what is explained. This is a place of education and empowerment -- adding unique insights to previously offered solutions can be quite valuable to researchers. – mickmackusa Mar 25 '20 at 23:56
  • 2
    For example, [this answer of mine](https://stackoverflow.com/a/52098132/2943403) was posted a month after the same technique was posted. I was going to write a comment under the earlier answer, but as I typed out all of the information that I wanted to offer, it was obviously too much to sensibly comment. I posted a new answer and added lots of complimentary insights and background information regarding the technique and included a benchmark. This is how a non-unique solution can be valuable to researchers. – mickmackusa Mar 26 '20 at 00:01
  • 1
    This should be marked as answer – theking2 Jan 14 '23 at 11:23
18

I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest

substr(trim($string), -1)

EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.

trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:

$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);
Slashback
  • 541
  • 5
  • 9
11

As of PHP 8 you can now use str_ends_with()

$string = 'testers';
if (\str_ends_with($string, 's') {
    // yes
}
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
6

I'd advise to go for Gordon's solution as it is more performant than substr():

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

outputs something like

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds
Xenonite
  • 1,823
  • 4
  • 26
  • 39
  • 3
    This should be a comment on Gordon's answer. – Goose Nov 23 '15 at 20:42
  • 1
    Can confirm this. The longer your string is, the bigger is the performance difference. In my test with 10 characters substr is around 20 % slower – Philipp Feb 29 '16 at 21:09
  • Not surprising as substr() has the overhead of a function call and the other is "C like" direct string manipulation. BTW I ran this code on PHP 7.1-dev with the results: substr() took 7.090255022049seconds \ array access took 2.3145787715912seconds – RyanNerd Mar 12 '16 at 00:10
4

Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).

I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.

FastTrack
  • 8,810
  • 14
  • 57
  • 78
2

You can find last character using php many ways like substr() and mb_substr().

If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr

Here i can show you both example:

<?php
    echo substr("testers", -1);
    echo mb_substr("testers", -1);
?>

LIVE DEMO

Faisal
  • 4,591
  • 3
  • 40
  • 49
1

A string in different languages including C sharp and PHP is also considered an array of characters.

Knowing that in theory array operations should be faster than string ones you could do,

$foo = "bar";


$lastChar = strlen($foo) -1;
echo $foo[$lastChar];

$firstChar = 0;
echo $foo[$firstChar];

However, standard array functions like

count();

will not work on a string.

0

Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);

  • 1
    Why offer the same solution as this [answer](https://stackoverflow.com/a/2681810/2915423) more than ten years later? – helvete Oct 07 '20 at 13:47
-3

Siemano, get only php files from selected directory:

$dir    = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);


foreach($files as $file){
  $n = substr($file, -3);
  if($n == 'php'){
    echo $file.'<br />';
  }
}