Reputation: 2186
I wanted to make a simple shopping cart which takes a $_GET variable and puts it in the $_SESSION variable. The code I have tried is this:
<?php
session_start();
if (is_numeric($_GET['add'])) $_SESSION[(string)$_GET['add']] = 1; ?>
Because my item ids are numeric so I check first to stop random things to be added to the session variable. I then then do a var_dump to see the result. The first time I run the code with ?add=102 I get:
array(1) { [102]=> int(1) }
I then run the script again with ?add=108 I get:
array(1) { [108]=> int(1) }
What I want is:
array(2) { ["102"]=> int(1), ["108"]=> int(1) }
What am I doing wrong? My concept is to convert the $_GET variable to a string and store the quantity 1 and the string value of $_GET in $_SESSION associatively. This should allow me to add as many items as long as their id is not the same, which is what I want.
Here is alternatives I have tried:
strval($_GET['add']),
(string)($_GET['add']),
$_GET['add']
Nothing seems to work.
Any help would be appreciated.
Upvotes: 0
Views: 85
Reputation: 46
You cannot use $_SESSION
keys that are numeric.
Create another array in the session, e.g. $_SESSION['items']
Then:
session_start();
if(is_numeric($_GET['add']))
{
$_SESSION['items'][(string)$_GET['add']] = 1;
}
It's much easier to iterate over this items array later, when you have other information in your session.
Upvotes: 3
Reputation: 94642
I realise this is an amalgamation of Satya's comment and mthie's answer but the complete answer should I think be
add to
the array each time rather than overwrite
it so try
<?php
session_start();
if(is_numeric($_GET['add'])) {
$_SESSION['add'][][(string)$_GET['add']] = 1;
}
?>
Upvotes: 0