This article demonstrates how to get the last character of a string in PHP.

You can use the substr() function to find the last character of a single-byte string in PHP. It extracts the substring from the string as per the specified offset and length. To get the last character, you can pass an offset of -1 to substr() with its length parameter omitted. Note that when offset is negative, the returned string will start at that position from the string’s end.

Download  Run Code

 
Alternatively, you can use the string offset access syntax to access any character of a string. You could use square brackets ([]) for accessing string offset. The curly brace syntax ({}), on the other hand, has been deprecated since PHP 7.4 and is no longer supported in PHP 8.0.

Download  Run Code

 
To avoid the uninitialized string offset warning, it is recommended to check the string’s length before accessing the string offset. This can be easily done using the strlen() function. The negative numeric indices are also supported since PHP 7.1.

Download  Run Code

 
Checking the string’s length before accessing its offset is a little verbose. A better alternative to removing warning messages in PHP is the @ error control operator. When you place @ in front of an expression or a function call in PHP, any diagnostic error or warning generated by that expression or function will be suppressed. Here’s the compact, readable, and cleaner version of the above program:

Download  Run Code

 
Note that all the above solutions will only work for single-byte character sets, which represent the ASCII character set, and the character sets for several European languages. If you need to work with multibyte strings that use multibyte-character set (MBCS) encoding, consider using the mb_substr() function.

Download  Run Code

That’s all about getting the last character of a string in PHP.