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?
13 Answers
substr("testers", -1); // returns "s"
Or, for multibyte strings :
mb_substr("multibyte string…", -1); // returns "…"
-
131If you’re using multibyte character encodings like UTF-8, use
mb_substr
(php.net/mb_substr) instead.– GumboApr 21, 2010 at 10:19 -
12so much for my substr($string, strlen($string)-1, 1);. Seems I've taken the LONG way around!– jeffkeeMar 19, 2014 at 22:58
-
6You 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 FossMar 16, 2015 at 17:50
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];
-
3I like this C style answer, I wonder why this has only got this few upvotes. Jun 19, 2014 at 16:04
-
24
-
2I think this is a better solution because it allows you to modify the character, whereas the substr solution given above does not.– cazortAug 19, 2017 at 15:16
-
1
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
-
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.– user4023224Jun 7, 2017 at 1:28
-
2@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– RyanNerdOct 24, 2018 at 8:50
-
1$string{1} will be deprecated in PHP 7.4 (RFC: wiki.php.net/rfc/deprecate_curly_braces_array_access) Oct 7, 2019 at 20:43
-
1It spells
readablilty
. I assume he meantreadability
? Yes, 5 years later, I was curious lol.– WadeJul 17, 2021 at 5:20 -
1IMPORTANT: when the string is empty, it will thow an error
PHP Notice: Uninitialized string offset: -1
. So, check that before.– sdlinsSep 6, 2021 at 17:57
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]
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)
-
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. Mar 25, 2020 at 10:05
-
1@mickmackusa Why did you write it only to me and ignored the multiple variations substr()?– nektobitMar 25, 2020 at 23:35
-
1Nothing 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. Mar 25, 2020 at 23:56
-
2For 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. Mar 26, 2020 at 0:01
-
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);
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
-
1Can confirm this. The longer your string is, the bigger is the performance difference. In my test with 10 characters substr is around 20 % slower– PhilippFeb 29, 2016 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– RyanNerdMar 12, 2016 at 0:10
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.
As of PHP 8 you can now use str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
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);
?>
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.
Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);
-
1
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 />';
}
}
s($str)->end()
helpful, as found in this standalone library.