[英]Array & Session - Different between 'var' and $var
I'm trying to understand PHP array right now. 我正在尝试了解PHP数组。 What's the different between
两者之间有什么不同
$_SESSION['var'] and $_SESSION[$var]? $ _SESSION ['var']和$ _SESSION [$ var]?
And how and when can we access variable like this - $_SESSION[$var][1]? 以及如何以及何时才能访问这样的变量-$ _SESSION [$ var] [1]?
Thanks! 谢谢! :D
:D
If you use $var as an array index, the value of $var will be used as the index: 如果将$ var用作数组索引,则$ var的值将用作索引:
$var = "foo";
$_SESSION['foo'] = "bar";
$_SESSION['var'] = "variable";
echo $_SESSION['var']; // This will echo "variable"
echo $_SESSION[$var]; // This will echo "bar"
As for your second example, in $_SESSION[$var][1] the string contained in $_SESSION[$var] will be accessed as an array of letters, returning the character in index 1 - the second letter. 关于第二个示例,在$ _SESSION [$ var] [1]中,包含在$ _SESSION [$ var]中的字符串将作为字母数组访问,返回索引1中的字符-第二个字母。
In the former, 'var' is the "key" of the $_SESSION array. 在前一种情况下,“ var”是$ _SESSION数组的“键”。 In the latter, the variable $var holds a value which is the "key" of the $_SESSION array.
在后者中,变量$ var保留一个值,该值是$ _SESSION数组的“键”。
With $_SESSION['var']
you specify the value with the key var
; 使用
$_SESSION['var']
您可以使用关键字var
指定值; with $_SESSION[$var]
you specify the value with the key with the value of $var
: 与
$_SESSION[$var]
指定用价值的关键价值$var
:
$arr = array('var' => 1, 'foo' => 2);
$var = 'foo';
var_dump($arr['var']); // int(1)
var_dump($arr[$var]); // int(2)
And before the question arises: $arr["$var"]
is equivalent to $arr[$var]
(here $var
is converted to string internally). 在出现问题之前:
$arr["$var"]
等效于$arr[$var]
(此处$var
在内部转换为字符串)。 And although $arr[var]
is handled equivalently as $var['var']
, you shouldn't use the former. 尽管
$arr[var]
与$var['var']
等效,但您不应使用前者。 See also Array dos and don'ts . 另请参见数组“注意事项” 。
$var is an variable 'var' is an string. $ var是变量'var'是字符串。 If you say
如果你说
$_SESSION['my_string'] = 1;
this would be the same as 这将与
$anything = 'my_string';
$_SESSION[$anything] = 1;
because $anything is 'my_string'. 因为$ anything是'my_string'。 In this example:
在此示例中:
$_SESSION['test'] = 'test output';
$demo = 'demo';
$_SESSION[$demo] = 'demo output';
echo $_SESSION['test']; // outputs "test output"
echo $_SESSION['demo']; // outputs "demo output" and is the same as:
echo $_SESSION[$demo]; // outputs "demo output".
you can see how it works. 您可以看到它的工作原理。
on the second question, there is no problem accessing them, just like you said: 在第二个问题上,访问它们没有问题,就像您说的那样:
$_SESSION[$first][$second]. $ _SESSION [$ first] [$ second]。
on the first answer, see Kaivosukeltaja, he has given a great answer 在第一个答案上,看到Kaivosukeltaja,他给出了一个很好的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.