Re: Reasoning behind using quotes for associative array element acces s?
| From: | Lars Torben Wilson | Date: | Fri, 11 Aug 2000 22:21:53 +0000 |
| Subject: | Re: Reasoning behind using quotes for associative array element acces s? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-11424@lists.php.net to get a copy of this message | ||
Christensen, BruceX R writes:
> What's the purpose of having $myarray["element"] be legal, while
> $myarray[element] is "illegal"? When I was first learning PHP, I did it the
> Perl way, without the quotes. I have since discovered that this is "bad",
> but I don't understand why. It works both ways (albeit with a warning if
> error reporting is turned up above the default), and so I can do something
> like $myarray["value$num"] if necessary, but most of the time,
> $myarray[element] is quicker.
>
> Any hazards of doing it w/o quotes?
>
> Ideas? Rasmus? Zeev?
>
> --Bruce
>
> Bruce Christensen
> Intel Corporation
> brucex.r.christensen@intel.com
As a quick example, try the following:
<?php
$myarray = array ('default' => 'DEFAULT');
echo $myarray['default'];
?>
Try it without the quotes. You'll get a parse error.
The reason is that when PHP sees a word without quotes, it first tries
to figure out whether that word has any special meaning (i.e.,
'default', without quotes, is a part of a switch() statement). Only if
no other meaning is found will the word be interpreted as a string. So
while most words will work fine in this context without quotes, since
PHP has no other meaning for them, any keywords will be interpreted as
being out of place, and generate a parse error.
So the safe thing to do is use quotes. Even if a given string is not a
keyword now, maybe it will be later.
Torben
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+