Any difference between $arr['key'] and $arr[key]
Could someone tell me if there's a difference between $arr['key'] and $arr[key] (without quotation marks)? Thanks.
$arr['key'] is an element of an associative array as opposed to an indexed array.
I have always had the associative array key enclosed in single quotes because that is the way I was taught and so have always assumed an error would be generated if the quotes were omitted - but I could be wrong.
Why, what happens if you echo $arr[key]? Did you not get an error?
Unless you are thinking of $arr[$someVar] which is valid if $someVar is a string or integer
Last edited by tirna; 07-28-2010 at 07:50 AM.
If the quotes are omitted the php engine checks for a constant. If the constant doesn't exist then it throws a "notice" error a "corrects" the quotes for you. It is better practice to use the quotes (unless you are indeed referencing a constant).
The problem is one of forward compatibility. $arr[key] might work today but one day in the future key might be a constant.
“The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
—Tim Berners-Lee, W3C Director and inventor of the World Wide Web
php.net now say it's wrong, except when parsed in a string.
Last edited by Declan1991; 07-28-2010 at 10:18 AM.
Great wit and madness are near allied, and fine a line their bounds divide.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)