Access to PHP array without quotes

I knocked on a phenomenon in an existing php source, with access to a field without an apostrophe as follows: $ _GET [test].

I am not sure, nor do I know that this is a possible way, so I wrote a short example for testing:

echo "Array Test, fields without apostrophe, like \$_GET[fieldname]<BR><BR>"; $a = array(); $a['test'] = "ArrayValue"; echo "case 1 -> \$a['test']: " . $a['test'] . "<BR>"; echo "case 2 -> \$a[\"test\"]: " . $a["test"] . "<BR>"; echo "case 3 -> \$a[test]: " . $a[test] . "<BR>"; 

And it works, each result got a value (ArrayValue).

I prefer the access method as case 2.

Is case 3 a normal, valid coding style in php?

+6
source share
3 answers

What happens here is that PHP sees a constant called test . If the constant is defined, the value is returned, it is not defined, PHP returns to the string "test" . For instance:

 $array = array("A" => "Foo", "B" => "Bar", "C" => "Baz") define("B", "C"); echo $array[A]; // The constant "A" is undefined, // so PHP falls back to the string "A", // which has the value "Foo". echo $array["B"]; // The result is "Bar". echo $array[B]; // The value of constant "B" is the string "C". // The result is "Baz". 

This is for backward compatibility, and you should never use it. If you turn on notifications , you'll see that PHP is complaining about this.

+7
source

If you do not put the key in quotation marks, it will be treated as an undefined constant (provided that it is not defined anywhere), which may still work, but may be unsuccessful in future versions of PHP. Therefore, this is simply wrong, and this option is also incorrect in the PHP documentation. Check Arrays do and do not .

By the way: if you insert the key in double quotes, it displays the variables inside the key-name.

+4
source

Using array key names without quotes is an obsolete function in PHP. This was originally done, but it is no longer recommended and is only supported for backward compatibility. It will give a warning message if you have strict mode enabled.

The reason she works is because she sees the key name in this form as a constant. When PHP sees an unknown constant, the constant name is used as the value by default, so it works like a string replacement.

This would break if you had define() elsewhere in your program that set the value of this constant. It also does not work if your keyword name contains spaces, starts with a digit, or is an invalid permanent name for any other reason.

For these reasons, this method is not recommended.

But first of all, PHP developers have publicly stated that this is not a good practice, which may well mean that future versions of PHP exclude the possibility of writing such code.

+1
source

All Articles