00 Votes

PHP: Can I use Arrays as Session Variables?

Question by Guest | 2014-06-28 at 13:48

Up to now, I have only used simple data types such as string, boolean or integer in my PHP sessions.

However, for a more complex project I am working at the moment, it would be nice if I could use an array as session variable (instead of multiple individual variables).

So, my question is whether it is possible to use also arrays as session variables? Or can this lead to any problems?

ReplyPositiveNegative
0Best Answer0 Votes

PHP also supports arrays as session variables.

You can just assign an array to any session variable like this:

$arr = array(1, 2, 3);
session_start();
$_SESSION['arr'] = $arr;

Or you can directly create your array in the session variable:

session_start();
$_SESSION['arr'] = array(1, 2, 3);

Accessing the array can be done like this, for example:

echo $_SESSION['arr'][0];  // 1

However, you can just use your session array variable like any other local array variable, too.
2014-06-29 at 14:07

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.