Avatar ·

How to get the last character of a string in PHP?

Hello everyone! I just started learning PHP and encountered this task: I need to get the last character from a string. For example, there is a variable:\n\n```php\n$string = "Hello, world!";\n```\n\nI want to get "!" — the last character. I tried using `$string[-1]`, but it gives an error "Uninitialized string offset". Then I read that in old PHP versions this is not allowed, but in new ones it is, but it's somehow unclear. Tell me how to do this correctly and reliably? Preferably, the code should work on all PHP versions, including outdated ones.\n\nAnother question: what to do if the string is empty? Sometimes the string comes from a form and can be empty, then trying to get the last character causes an error. Do I need to check the string length in advance?\n\nThanks in advance for your help! I would be grateful for any advice.