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?

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Bare string conversion also produces a warning. This sample here doesn't. Wrong explanation.
in the section that i've linked it is explained I don't want to paste whole manual here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.