Array & Session - Different between 'var' and $var
I'm trying to understa开发者_Go百科nd PHP array right now. What's the different between
$_SESSION['var'] and $_SESSION[$var]?
And how and when can we access variable like this - $_SESSION[$var][1]?
Thanks! :D
If you use $var as an array index, the value of $var will be used as the index:
$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.
In the former, 'var' is the "key" of the $_SESSION array. In the latter, the variable $var holds a value which is the "key" of the $_SESSION array.
$var is an variable 'var' is an string. If you say
$_SESSION['my_string'] = 1;
this would be the same as
$anything = 'my_string';
$_SESSION[$anything] = 1;
because $anything is '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].
on the first answer, see Kaivosukeltaja, he has given a great answer
With $_SESSION['var']
you specify the value with the key var
; with $_SESSION[$var]
you specify the value with the key with the value of $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). And although $arr[var]
is handled equivalently as $var['var']
, you shouldn’t use the former. See also Array dos and don’ts.
精彩评论