Programming Tips - How do I get the last character of a string (with PHP) ?

Date: 2009nov30 Updated: 2018nov20 Language: php Q. How do I get the last character of a string (with PHP) ? A. Using a negative offset for substr is a nice way...
$str = 'abc'; $last_char = substr($str, -1, 1) # As a funciton with error checking function lastChar($str) { if ($str == '') return ''; return substr($str, -1, 1) } # Another way function lastChar($str) { $len = strlen($str); if ($len == 0) return ''; return $str[$len - 1]; } # For completeness function firstChar($str) { $len = strlen($str); if ($len == 0) return ''; return $str[0]; }