Possible Duplicate:
Is it okay to use array[key] in PHP?
Is there any significant different between
$test['car']
and $test[car]
Both produce same result.
Possible Duplicate:
Is it okay to use array[key] in PHP?
Is there any significant different between
$test['car']
and $test[car]
Both produce same result.
In $test[car]
, car
is expected to be a constant. Constants are bare words without quotes or preceding $
. If you do not have a constant named car
defined, PHP will assume you meant 'car'
. That's very bad behavior, but it is what it is. If you'd activate error reporting as you should during development, you'd see a lot of errors pointing this out.
They don't necessarily produce the same result. Try this code:
define('car', 'plain');
echo $test['car'] . "\n";
echo $test[car];
The version without the quotes doesn't use the word "car" as the index - instead it uses a constant with the name "car". If that constant is not defined, then the value of the constant is assumed to be the name of it. Hence you get the same results when using it in your case. However in my example, the results will be different.
The former is correct; the latter is a side effect of a (rather bad) choice of the PHP designers.
The reason why $test[car]
works at all and doesn't just crash with a syntax error is because PHP treats bare words (unrecognized symbols that aren't prefixed with $
) as constants, and it treats undefined constants as equivalent to a string with the name of the constant. Thus car
is equivalent to 'car'
if you haven't defined the constant car
via define()
.
Please, for the love of all that is good and happy, do not rely on this functionality. It is a potential maintenance nightmare waiting to happen. (And in fact, if you have display of Notice-level messages turned on PHP, you'll see a message about the usage of an undefined constant.)
Use $test['car']
.
There is the difference for the strings that happened to be array keys.
So, using just 'car'
and car
without arrays will have exactly the same effect.
'car'
is a string and car
is an extremely bad PHP feature: it is actually a constant
, which, it none of that name found, treated as a string.
The output though is not the same, $test[car]
will produce an error message. An should be never, ever used.
As for the arrays - almost any PHP statement can be used inside of []
braces - a string, a variable, a constant, a logical operator, a function call, etc.