In this article, we look at quick and easy ways to get the last character of a string in PHP. For all the examples in this article, let's assume we have the following strings:
$string = 'foo';
$multibyte = 'foo♥';
#Using Negative String Offset
// PHP 7.1+
$string[-1]; // outputs: 'o'
$multibyte[-1]; // outputs: '�'
Using this method is not multibyte safe. It works only with strings that are in a single-byte encoding (for example ISO-8859-1).
Using this method would trigger an E_NOTICE for PHP versions below 7.1 for reading, and an E_WARNING for writing.
#Using substr()
substr($string, -1); // outputs: 'o'
substr($multibyte, -1); // outputs: '�'
mb_substr($multibyte, -1); // outputs: '♥'
When you're using multibyte character encodings (for e.g. UTF-8), you might have to use the multibyte variant of the function (i.e. mb_substr()). That might only be necessary though, if a character in the string is represented by two or more consecutive bytes. The reason behind this is because the regular substr() function is not multibyte-aware and would fail to detect the beginning or end of the multibyte character which would result in incorrect / corrupted result.
#Using Direct String Access
$string[strlen($string)-1]; // outputs: 'o'
$multibyte[strlen($multibyte)-1]; // outputs: '�'
Using this method is not multibyte safe. It works only with strings that are in a single-byte encoding (for example ISO-8859-1).