Wednesday, March 16, 2011

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 []?

Thanks.

From stackoverflow
  • use $string[0], the other method (braces) is being deprecated in PHP6 (src)

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

    Jay : Will the use of {} as a method of evaluation be removed also? E.g ${$dynamic_object_name}->doStuff()
    Owen : nope, i believe their goal is to just standardize accessing strings as array.

0 comments:

Post a Comment