Why can't I use intergers as an index in a PHP $ _SESSION array?

For instance:

$_SESSION['1'] = 'username'; // works
$_SESSION[1] = 'username'; //doesnt work

I want to store the index of a session array as an array index. So o / p:

Array(
[1] => 'username'
)
+5
source share
3 answers

$_SESSION can only be used as an associative array.

You could do something like this:

$_SESSION['normal_array'] = array();
$_SESSION['normal_array'][0] = 'index 0';
$_SESSION['normal_array'][1] = 'index 1';

Personally, I just stick with an associative array.

$_SESSION['username'] = 'someuser';

or

$_SESSION['username_id'] = 23;
+9
source

I suspect this is probably because the $ _SESSION array is just an associative array. Also, since the PHP manual puts:

The keys in the association $ _SESSION array obey the same restrictions as regular variable names in PHP, that is, they cannot number and must begin with a letter or underscore.

, NOTICE? (, .) .

+5

You can also use this approach to save an array dimension:

$_SESSION['form_'.$form_id] = $form_name;

which might look like this:

$_SESSION['form_21'] = 'Patient Evaluation';

Unlike:

$_SESSION['form'][21] = 'Patient Evaluation';

which uses another dimension of the array.

0
source

All Articles