In this example, we will show you how to get last char from defined string.
In this post there are three solution for getting the last char from PHP strings.
Get the Last Character of a String
Solution 1: In the first solution we used substr()
function.
Substr: returns the portion of string specified by the offset and length parameters.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $str = "Code4Example"; //Get Last character from a string $result = substr($str, strlen($str)-1); echo $result; ?> |
Output:
1 2 3 |
e |
Solution 2: mb_substr function will help you when working multi byte chars(any utf-8 chars).
Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of string
. First character’s position is 0. Second character position is 1, and so on.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $str = "こんにちは世界"; //Get Last character from a string $result = mb_substr($str, -1); echo $result; ?> |
Output:
1 2 3 |
界 |
[…] You may also like: How to get the last character of a string in PHP […]