JasonDavis
JasonDavis

Reputation: 48933

Do PHP array keys need to we wrapped in quotes?

Which one below is correct? First code has no quotes in the $_GET array and the second one does, I know you are supposed to have them when it is a string of text but in this case it is a variable, also what about if the key is a number?

no quotes

function arg_p($name, $default = null) {
  return (isset($_GET[$name])) ? $_GET[$name] : $default;
}

with quotes

function arg_p($name, $default = null) {
  return (isset($_GET['$name'])) ? $_GET['$name'] : $default;
}

Upvotes: 1

Views: 4943

Answers (3)

snicker
snicker

Reputation: 6148

With PHP, $_GET["$name"] and $_GET[$name] are identical, because PHP will evaluate variables inside double-quotes. This will return the key of whatever the variable $name stores.

However, $_GET['$name'] will search for the key of $name itself, not whatever the variable $name contains.

If the key is a number, $_GET[6], $_GET['6'], and $_GET["6"] are all syntactically equal.

Upvotes: 7

Ayoub M.
Ayoub M.

Reputation: 4798

  • if the key is a variable

    $array[$key];

you don't have to quote it.

  • but if it a literal string you must (it is not a string if you don't wrap it in quotes)

    $array['myKey'];

and you will get an notice if you do it like this

$array[mykey];

Upvotes: 2

Gumbo
Gumbo

Reputation: 655139

The first one will use the value of $name as key while the second will use the literal string '$name' as key.

Upvotes: 10

Related Questions