Get last character of a string in PHP
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.
|
1 2 3 4 5 6 |
<?php $string = 'Hello, Techie'; $last = substr($string, -1); echo $last; // prints e ?> |
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.
|
1 2 3 4 5 6 |
<?php $string = 'Hello, Techie'; $last = $string[strlen($string) - 1]; echo $last; // prints e ?> |
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.
|
1 2 3 4 5 6 |
<?php $string = 'Hello, Techie'; $last = strlen($string) > 0 ? $string[-1]: ''; echo $last; // prints e ?> |
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:
|
1 2 3 4 5 6 |
<?php $string = 'Hello, Techie'; $last = @$string[-1]; echo $last; // prints e ?> |
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.
|
1 2 3 4 5 6 |
<?php $string = '最後の文字を削除'; $last = mb_substr($string, -1); echo $last; // prints 除 ?> |
That’s all about getting the last character of a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)