Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PHP require double quotes for key variable in adding array key-value pairs?

Tags:

php

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!

like image 959
user3388884 Avatar asked Oct 18 '25 13:10

user3388884


2 Answers

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.

like image 189
deceze Avatar answered Oct 20 '25 04:10

deceze


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.

like image 22
Ray Avatar answered Oct 20 '25 03:10

Ray