How to get the last char of a string in PHP?

PhpString

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Or, for multibyte strings :

mb_substr("multibyte string…", -1); // returns "…"

Solution 2 - Php

substr($string, -1) 

Solution 3 - Php

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

Solution 4 - Php

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 https://stackoverflow.com/users/3996393/xenonite">xenonite's</a> performance code with these results:

> substr() took 7.0334868431091seconds

> array access took 2.3111131191254seconds

> Direct string access (negative string offsets) took 1.7971360683441seconds

Solution 5 - Php

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)

Solution 6 - Php

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

Solution 7 - Php

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

Solution 8 - Php

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.

Solution 9 - Php

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

Solution 10 - Php

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.

Solution 11 - Php

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

Solution 12 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstreetparadeView Question on Stackoverflow
Solution 1 - PhpRich AdamsView Answer on Stackoverflow
Solution 2 - PhpknittlView Answer on Stackoverflow
Solution 3 - PhpGordonView Answer on Stackoverflow
Solution 4 - PhpRyanNerdView Answer on Stackoverflow
Solution 5 - PhpnektobitView Answer on Stackoverflow
Solution 6 - PhpSlashbackView Answer on Stackoverflow
Solution 7 - PhpXenoniteView Answer on Stackoverflow
Solution 8 - PhpFastTrackView Answer on Stackoverflow
Solution 9 - PhpFaisalView Answer on Stackoverflow
Solution 10 - PhpPetar AtanasovView Answer on Stackoverflow
Solution 11 - PhpWHY SO SERIOUS -DView Answer on Stackoverflow
Solution 12 - PhpZMORA PROSTO Z KRZOKAView Answer on Stackoverflow