Why does PHP require double quotes for key variable in adding array key-value pairs?
php
Solution
You do not require double quotes. `$envArr[$env]` is perfectly legal syntax. `$envArr['$env']` would create the literal key `'$env'`, which is not what you want.
However, if `$env` is not a string or integer, but, say, an object or `null`, that's when you'd get an illegal offset notice. Interpolating the variable into a string with `"$env"` forces the variable to be cast to a string, which avoids that problem. But then arguably the problem is that you're trying to use a non-string as array offset, so an error message would be perfectly justified and preferable.
I'd be guessing that you're using SimpleXML and `$env` is a `SimpleXMLElement` object. You should be using this then:
$envArr[(string)$env]
// or
$envArr[$env->__toString()]
That's basically the same as encasing the variable in double quotes, it forces a string cast, but in this case it's explicit and not a mystery.
Problem
Why does PHP require double quotes for key variable in adding array key-value pairs? ``` foreach($coreXml->Environment as $Environment) { $env = $Environment->Name; $envArr["$env"] ="test"; } ``` In this loop, if I don't use double quotes around the $env or use single quotes, it will break the code with error "Illegal offset type". Any idea on why that is? thanks!