In this post, we’ll show you how to easily retrieve the last character of a string in PHP. There are multiple ways to achieve this, and we’ll explore three different methods.
Solution 1: Using the substr()
Function
The substr()
function in PHP is commonly used to extract a part of a string. You can specify the starting point and the length to extract the substring. To get the last character, we use the length of the string minus one as the starting position.
Example:
1 2 3 4 5 6 7 8 9 10 11 | <?php $str = "Code4Example"; // Get the last character from the string $result = substr($str, strlen($str) - 1); echo $result; // Output: e ?> |
Explanation:
strlen($str)
gives the length of the string.substr($str, strlen($str) - 1)
extracts the character starting from the last position.
Output:
1 2 3 | e |
Solution 2: Using the mb_substr()
Function
If you are working with multi-byte characters (e.g., UTF-8 characters), the mb_substr()
function is a better choice. This function safely handles multi-byte characters, unlike substr()
which may not work well with characters like emoji or certain international characters.
Example:
1 2 3 4 5 6 7 8 9 10 11 | <?php $str = "こんにちは世界"; // Get the last character from the string $result = mb_substr($str, -1); echo $result; // Output: 世 ?> |
Explanation:
- The
mb_substr()
function takes a negative index to count from the end of the string. - Here,
-1
tellsmb_substr()
to return the last character of the string.
Output:
1 2 3 | 世 |
Conclusion
These two solutions provide effective ways to retrieve the last character of a string in PHP:
substr()
: Use it when working with regular strings.mb_substr()
: Use it when dealing with multi-byte or UTF-8 characters to ensure proper handling.
Both methods are quick and efficient depending on your needs. If you’re dealing with special characters, it’s safer to go with mb_substr()
.
[…] You may also like: How to get the last character of a string in PHP […]