What does this PHP syntax mean?

Consider the code:

$a = "foobar"; echo $a{3}; // prints b 

I know that $a[3] is 'b' , but why does using {} instead of [] produce the same result?

+6
syntax php
source share
4 answers

You can read it here in the official braces documentation :

Strings s can also be accessed using brackets, as in $ str {42}, for the same purpose. However, this syntax is deprecated from PHP 5.3.0. Use a square instead of brackets, for example $ str [42].

+10
source share

EDIT This topic might interest you: "removing curly braces"

This is just an alternative syntax; two forms are compiled to the exact 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
+6
source share

Same thing, but the syntax {} deprecated since PHP 5.3.

+5
source share

{} and [] match. It is your choice what to use. [] is more common.

0
source share

All Articles