Search code examples
phparraysapostrophe

PHP Array access without quotes


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

I got unsure, also don't 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, every result got the value (ArrayValue).

I prefer the access method like case 2.

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


Solution

  • What happens here, is that PHP sees a constant called test. If the constant is defined, the value is returned, it isn't defined, PHP falls back to the string "test". For example:

    $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".
    

    It's for backwards compatibility and you should never use it. If you'll turn on notices, you'll see that PHP complains about it.