Access to arrays without quoting a key

I can access the value of the array using $array[key]or$array['key']

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

+3
source share
3 answers

Use the last option $array['key']. The first will only work because PHP is tolerant and accepts a string value keyif there is no persistent named key:

Always use quotation marks around the string literal index. For example, it is $foo['bar']true, but $foo[bar]not. [...] This is wrong, but it works. The reason is that this [...] has the constant undefined ( bar), and not a string ( 'bar'- note the quotation marks).

. Array do and don'ts.

, PHP-, :

[...] , , , "$foo[bar]" . . , , .

:

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

// valid
echo "$array[key]";
echo "{$array['key']}";
+6

PHP ($array[key]), key $array['key']. , , - :

$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]}";

, , (error_reporting(E_ALL) display_errors(1))

+2

$array[key] . "" (.. define()) . , , PHP , "" "" , .

0

Source: https://habr.com/ru/post/1768633/


All Articles