PHP数组键是否需要用引号括起来?

Jas*_*vis 1 php arrays syntax

下面哪一个是正确的?第一个代码在$ _GET数组中没有引号,第二个代码没有引号,我知道当它是一个文本字符串时你应该有它们但在这种情况下它是一个变量,如果键是一个数字呢?

没有报价

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

带引号

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

Gum*_*mbo 10

第一个将使用$nameas键的值,而第二个将使用文字字符串'$name'作为键.

  • @jasondavis:我认为你的意思是*未知偏移*/*未知索引*通知.那是因为您应该在尝试阅读之前测试该项是否存在.一种方法是`isset`,另一种是`array_key_exists`. (3认同)

sni*_*ker 7

使用PHP,$_GET["$name"]并且$_GET[$name]是相同的,因为PHP将在双引号内评估变量.这将返回变量$name存储的密钥.

但是,$_GET['$name']将搜索$name自身的键,而不是变量$name包含的键.

如果键是一个数字,$_GET[6]$_GET['6'],并且$_GET["6"]在语法上都是相等的.