tags:

views:

131

answers:

6

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 ?

A: 

{} and [] are the same. it is your choice what to use. [] is more common though.

kgb
{} is deprecated, and shouldn't be used
fahadsadah
A: 

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
Bjorn
You are right but that was not the question ;)
Felix Kling
Sorry, my mind was wandering it seems :-) I've learn't from this now too, I had no idea array elements could be referenced like this too.
Bjorn
+5  A: 

It's the same, but the {} syntax is deprecated as of PHP 5.3.

Macmade
+10  A: 

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].

silent
+5  A: 

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
Artefacto
wow. can you please give a name of program that shows this table?
silent
@silent It's vld. See http://derickrethans.nl/projects.html
Artefacto
great, thank you!
silent