0

I'm having a little issue, when I do this:

$_SESSION['cartItems'] = array();

It works fine, and it creates a cartItems array in the session.

But when I do this:

$_SESSION[2]['cartItems'] = array();

This works until I refresh the page, then it forgets this session array?

I tried to create the 2 array first:

$_SESSION[2] = array();
$_SESSION[2]['cartItems'] = array();

But still does not work like it is supposed to do.

How can I solve this?

Lix
  • 47,311
  • 12
  • 103
  • 131
Karem
  • 17,615
  • 72
  • 178
  • 278
  • This page will tell you what you need! http://stackoverflow.com/questions/4574578/why-session-array-index-doesnt-accept-integer-as-array-index – Benz Jun 27 '13 at 11:45

2 Answers2

3

Numeric keys are converted to strings because the $_SESSION variable is an associative array. You might want to try using $_SESSION["2"] when assigning or retrieving values.

Further more, it looks to me like you are trying to persist several cart arrays, so why not use something like this instead:

$_SESSION['carts'] = array();
$_SESSION['carts'][0] = array();
$_SESSION['carts'][1] = array();
...

Or even $_SESSION['carts'][0]['cartItems'] = array()

Some related posts for further reading:

Community
  • 1
  • 1
Lix
  • 47,311
  • 12
  • 103
  • 131
-1

I suggest you to use as serialized object.

$_SESSION['carts'] = serialize(array(0=> "foo", 1=> array("bar")));

In this case you can store complex data and it will be secure & clean.

GirginSoft
  • 375
  • 3
  • 16
  • How exactly does serializing the object make it secure? Everyone has access to [unserialize](http://php.net/manual/en/function.unserialize.php). – Lix Jun 27 '13 at 12:04
  • How exactly does this make it clean? You'll have to unserialize -> serialize every time you want to touch the data... – Lix Jun 27 '13 at 12:05
  • If you don't serialize it you can access it everywhere also. There is no difference. It is more secure then store it open, it's my opinion. You can use function why you need to every time serialize and unserialize. Write a function to get session and set session. Of course it's not logical everytiem do it – GirginSoft Jun 27 '13 at 12:51