Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

Eg:

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

I want to store session array index as array index. So that o/p is :

Array(
[1] => 'username'
)
like image 828
Angelin Nadar Avatar asked Jan 01 '11 15:01

Angelin Nadar


People also ask

Can a session variable be an array PHP?

Yes, PHP supports arrays as session variables.

How do you register a variable in a session?

We can create the session by writing session_start() and destroy the session by using session_destroy(). You can access the session variable by writing $_session[“name”]. Let us understand how the session works from the following examples. Example 1: In the following, you can create the session by entering the name.

What is $_ session in PHP?

PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.


1 Answers

$_SESSION can only be used as an associative array.

You could do something like this though:

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

Personally, I'd just stick with the associative array.

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

Or

$_SESSION['username_id'] = 23;
like image 182
Luke Antins Avatar answered Oct 13 '22 05:10

Luke Antins