Get Last Character of String PHP


Getting the last character of a string with PHP is pretty simple, all you need is one line of code and your string that needs to be sliced.

Let’s take a demonstration string such as ‘This is my string!’

We need to grab the last character from the string which of course would be the exclamation mark.

For this task, substr() is the perfect function.

PHP

$string = "This is my string!";

$lastChar = substr($string, -1);

echo $lastChar; // outputs !

So, the substr() function accepts a string and some numeric parameters to ensure the correct parts of the string are stripped out.

In this case we use the string parameter which is our string and the second parameter as a -1 (offset), telling substr() to go to start at the end of the string and take the last character.

Check out the documentation on the substr() function for more complex examples.

 





Copyright 2023 Code Wall. All rights reserved.



Source link