Accessing characters in a string using array syntax

Okay, I'll aggregate my comments as an answer:

To quote the manual

Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 7 . Use square brackets instead.

Also, albeit undocumented, the {} accessor also works for arrays, which makes $foo{$bar} and $foo[$bar] completely equivalent. It's just old syntax for the convenience of Perl programmers.

Concerning your second question, if it is good practice to treat strings like an array of characters: Yes, if it is useful for your task, do it. In low level languages like C, strings are arrays of characters, so it is quite natural to treat them like that.

BUT keep in mind that PHP has bad unicode support. So if your string is in multi-byte encoding (ie UTF-8), this might not work as expected. Better use the multibyte functions in that case.


You can write "Hello, I am a character of a string $string{0}"

But you can not write "Hello, I am a character of a string $string[0]"

You have to use string concatenation sign like
"Hello, I am a character of a string " . $string[0];


https://www.php.net/manual/en/language.types.string.php

Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

So, always use square brackets $str[0].

Tags:

Php

String