String dereferencing or How to extract a single character from a string with PHP

String dereferencing allows you direct access to individual characters. The dereferencing syntax is just like accessing an array element by it’s index:

$string = 'This is my awesome string!'

echo 'First Character: ' . $string[0] . "n"
echo 'Tenth Character: ' . $string[9] . "n"
echo 'Last Character: ' . $string[strlen($string) - 1] . "n"

Remember that the index starts at 0 just like an array would.

If you are running PHP 5.5+ you have the added benefit of being able to dereference string literals:

echo 'First Character: ' . 'This is my awesome string!'[0

Personally, I don’t really see any situation where I’d do this, but I guess someone thought it was a good thing to add support for. Hopefully in the coming PHP releases support for specifying ranges like you can in Python will be added (e.g. $string[0:9]).

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.