Getting the first character of a string with $str[0]


Question

I want to get the first letter of a string and I've noticed that $str[0] works great. I am just not sure whether this is 'good practice', as that notation is generally used with arrays. This feature doesn't seem to be very well documented so I'm turning to you guys to tell me if it's all right – in all respects – to use this notation?

Or should I just stick to the good ol' substr($str, 0, 1)?

Also, I noted that curly braces ($str{0}) works as well. What's up with that?

1
259
12/28/2009 11:27:21 PM

Accepted Answer

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

369
8/8/2017 4:14:47 AM

The {} syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon