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

by Yang Yang on March 14, 2009

Share This Article:
Subscribe to Kavoir: blog feed

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′.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 2 comments… read them below or add one }

JG March 17, 2009 at 8:37 pm

Why so complex?

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

Does the job, documented in the manual.

Reply

Yang Yang February 26, 2010 at 4:57 pm

Nice!

Reply

Leave a Comment

Previous post:

Next post: