tags:

views:

41

answers:

3

I can access an array value either with $array[key] or $array['key']

Is there a reason to avoid using one over the other?

+3  A: 

Use the latter variant $array['key']. The former will only work because PHP is tolerant and assumes the string value key if there is no constant named key:

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. […] This is wrong, but it works. The reason is that this […] has an undefined constant (bar) rather than a string ('bar' - notice the quotes).

See also Array do's and don'ts.

Now in opposite to accessing arrays in plain PHP code, when using variable parsing in double quoted strings you actually need to write it without quotes or use the curly brace syntax:

[…] inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

So:

// syntax error
echo "$array['key']";

// valid
echo "$array[key]";
echo "{$array['key']}";
Gumbo
A: 

$array[key] is not correct usage. In this case 'key' will be treated as a constant (i.e., via define()) instead of a string. In the case where there is no constant named key, PHP will assume you mean 'key' and "fix" it for you and throw a warning.

Alex Howansky
+2  A: 

PHP will raise a warning for the quote-less version ($array[key]) if there's no constant named keydefined, and silently convert it to $array['key']. Consider the trouble you'd have debugging your code if you had something:

$array['foo'] = 'baZ'
echo $array[foo];
echo $array['foo'];
echo "$array[foo]";
echo "{$array['foo']}";
echo "{$array[foo]}";

define('foo', 'baR');
echo $array[foo];
echo $array['foo'];
echo "$array[foo]";
echo "{$array['foo']}";
echo "{$array[foo]}";

Try them out and see, but make sure you've got warnings enabled (error_reporting(E_ALL) and display_errors(1))

Marc B