tags:

views:

239

answers:

3

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;
}
+8  A: 

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

Gumbo
OK good so $something[3]; would not show a NOTICE right?
jasondavis
@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
+5  A: 

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.

snicker
+1  A: 
  • 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
you won't get an error for $array[mykey]. you will only get a PHP Notice. check out http://thephpcode.blogspot.com/2009/09/php-speed-up-quote-your-strings.html for more about this.
thephpdeveloper
yes you it is true but still not good
Ayoub