PHP: Return and Get the Last Letter / Character of a String

To get the last character of a string in PHP, you need a combination of the functions of substr() and strlen().

For example, you need to get the last digit of a date string such as ‘Feb. 3’ or ‘Aug. 14’ to determine whether the trailing of the date will be ‘st’, ‘nd’, ‘rd’ or ‘th’.

Just go with this:

$str = 'Feb. 2';
$last = substr($str, strlen($str) - 1);
echo $last;

Then $last would be:

2

PHP function substr returns a slice of a string by the starting and ending positions while strlen returns the length of the string which should be subtracted by 1, would be the position of the last character in the string, in this case, ‘2’.

2 thoughts on “PHP: Return and Get the Last Letter / Character of a String”

  1. Why so complex?

    $str = ‘Feb. 2’;
    $last = substr($str, – 1);
    echo $last;

    Does the job, documented in the manual.

Comments are closed.

Scroll to Top