PHP $string{0} vs. $string[0];

In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:

$string = 'hello';

echo $string{0}; // h
echo $string[0]; // h

My question is, is there a benefit of one over the other? What’s the difference between {} and []?


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

use $string[0], the other method (braces) has been removed in PHP 8.0.

For strings:

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

And for arrays:

Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Solution 2

There is no difference. Owen’s answer is outdated, the latest version of PHP Manual no longer states that it is deprecated §:

Characters within strings may be accessed and modified by specifying
the zero-based offset of the desired character after the string using
square array brackets, as in $str[42]. Think of a string as an array
of characters for this purpose
. […]

Note: Strings may also be accessed using braces, as in $str{42}, for
the same purpose

However it seems that more people/projects use [], and that many people don’t even know {} is possible. If you need to share your code publicly or with people who don’t know the curly brace syntax, it may be beneficial to use [].

UPDATED : accessing string characters with {} is deprecated, use [] instead.

Solution 3

Yes, there’s no difference. This language quirk has some history…

Originally, the curly brace syntax was intended to replace the square bracket syntax which was going to be deprecated:

Later that policy was reversed, and the square brackets syntax was preferred instead:

and even later, the curly braces one was going to be deprecated:

As of this writing, it seems that the deprecation has been withdrawn as well and they are just considered two alternative syntaxes:

Solution 4

Curly brace access was deprecated in PHP 7.4

Array and string offset access using curly braces ¶

The array and string offset access syntax using curly braces is
deprecated. Use $var[$idx] instead of $var{$idx}.

PHP 7.4 Deprecated Features, PHP Core

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply