Consider the code:
$a = "foobar";
echo $a{3}; // prints b
I know $a[3]
is 'b'
but how come using {}
in place of []
produec the same result ?
Consider the code:
$a = "foobar";
echo $a{3}; // prints b
I know $a[3]
is 'b'
but how come using {}
in place of []
produec the same result ?
{} and [] are the same. it is your choice what to use. [] is more common though.
I'm guessing it would be the character at that position, starting from 0 of course.
echo $a{2}; // prints o
echo $a{0}; // prints f
You can read here in official documentation about braces:
String s may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].
EDIT This thread may interest you: "dropping curly braces"
It's just an alternative syntax; the two forms compile to exactly the same bytecode:
<?php
$str = "aaab";
echo $str{3};
echo $str[3];
number of ops: 9 compiled vars: !0 = $str line # * op fetch ext return operands --------------------------------------------------------------------------------- 2 0 > EXT_STMT 1 ASSIGN !0, 'aaab' 3 2 EXT_STMT 3 FETCH_DIM_R $1 !0, 3 4 ECHO $1 4 5 EXT_STMT 6 FETCH_DIM_R $2 !0, 3 7 ECHO $2 8 > RETURN 1