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!
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.
I'm guessing $env is null or an object. If null the case $envArr[""] would be the result of $envArr["$env"] It's perfectly fine to have an empty string index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With