583

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?

2

12 Answers 12

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

Or, for multibyte strings :

mb_substr("multibyte string…", -1); // returns "…"
Sign up to request clarification or add additional context in comments.

4 Comments

If you’re using multibyte character encodings like UTF-8, use mb_substr (php.net/mb_substr) instead.
so much for my substr($string, strlen($string)-1, 1);. Seems I've taken the LONG way around!
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.
Please see Yes Barry's answer. From PHP 8 you can use str_ends_with()
100
substr($string, -1) 

Comments

80

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];

4 Comments

I like this C style answer, I wonder why this has only got this few upvotes.
@ValentinMercier: Because this is a PHP question, not C.
I think this is a better solution because it allows you to modify the character, whereas the substr solution given above does not.
Note that this will throw a notice if the string is empty.
58

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

10 Comments

Thanks for posting benchmarks! If anyone is interested in C# benchmarks for doing the same thing, this page is a good read. Directly accessing the last character won out.
@TaufikNurRahmanda Technically there is no difference between [] and {}. The PHP developers gave the option to use either. For more details see: php.net/manual/en/migration71.new-features.php
$string{1} will be deprecated in PHP 7.4 (RFC: wiki.php.net/rfc/deprecate_curly_braces_array_access)
It spells readablilty. I assume he meant readability? Yes, 5 years later, I was curious lol.
IMPORTANT: when the string is empty, it will thow an error PHP Notice: Uninitialized string offset: -1. So, check that before.
|
38

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)

4 Comments

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.
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.
For example, this answer of mine 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.
This should be marked as answer
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);

Comments

15

As of PHP 8 you can now use str_ends_with()

$string = 'testers';
if (\str_ends_with($string, 's') {
    // yes
}

Comments

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

3 Comments

This should be a comment on Gordon's answer.
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
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
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.

Comments

3

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

Comments

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.

Comments

-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 />';
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.