1

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;
}
Kip
  • 107,154
  • 87
  • 232
  • 265
JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • Parenthesis is `()` and not `''`. The latter are single quotes or apostrophes. – Gumbo Sep 04 '09 at 20:09
  • When you say parentheses () are you referring to () or brackets []? If I'm not completely confused, or you've edited the post, it appears that the only difference between your two cases are the single quotes around '$name'. – dnagirl Sep 04 '09 at 20:12
  • 1
    Gumbo's answer is right. Also, I'd point out that in this case, the version without single-quotes is almost certainly an error. it would always behave the same, regardless of the value of $name. – Kip Sep 04 '09 at 20:15
  • Also, not trying to confuse you, but `$_GET["$name"]` would actually work the same as the version without quotes most of the time, but it is not correct – Kip Sep 04 '09 at 20:18
  • 1
    @kip: why is it an error? The function is meant to return a $_GET request variable if it exists with a value of $name, else return the value in $default. The first function is correct. – snicker Sep 04 '09 at 20:20
  • @snicker: I think @Kip meant "the version *WITH* single quotes", because that disables interpolation, so '$name' will always evaluate to '$name', regardless of the value of the $name variable. – Dan Dascalescu Jul 18 '11 at 02:51

3 Answers3

10

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 3
    @jasondavis: I assume you meant the *unknown offset*/*unknown index* notice. That’s because you should test if that item exists before trying to read it. One way to do that is `isset`, another `array_key_exists`. – Gumbo Sep 04 '09 at 20:22
7

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.

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
snicker
  • 6,080
  • 6
  • 43
  • 49
2
  • 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];
Ayoub M.
  • 4,690
  • 10
  • 42
  • 52