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

Josh Sherman
1 min read
Software Development 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]).

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles