0
$foo=['hello' => "Hello"]; 

echo $foo['hello']; // it works as we are doing in normal way
echo "$foo['hello']";  // it throws T_ENCAPSED_AND_WHITESPACE error when we use same variable double quote

echo $foo[hello];  // Throwing error Use of undefined constant.
echo  "$foo[hello]";   //  Strange!!! it WORKS because not checking constants are skipped in quotes

I am very surprised in echo "$foo[hello]"; because not checking hello index as constant. Exactly I want to know reason behind this?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42

2 Answers2

1

From manual:

It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

and

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

In manual see: Array do's and don'ts

Robert
  • 19,800
  • 5
  • 55
  • 85
1

Because that's how PHP's simple string parsing works. It's not PHP array syntax, it's string interpolation syntax.

Well documented: http://php.net/manual/en/language.types.string.php#language.types.string.parsing.

deceze
  • 510,633
  • 85
  • 743
  • 889