2

I have a session var for a shopping cart that reads: 'cart_b_1_1'.

The letter in the string indicates a category, the ints represent user id & product id.

How can I check the category of an already set SESSION var to see if it matches the category of a new selection?

I am trying to make sure that if an item is added to the SESSION array and there is a var that already exists with the same category letter, then it is unset and effectively replaced with the new selection. This is to limit selections by category to one.

Thanks for the help in advance.

2
  • You can have more than one value in the session. Why not use a variable for each value (category, user id, product id)?
    – CodeZombie
    Jun 13, 2012 at 20:36
  • iterate over array_keys of $_SESSION, if you find a key that preg_matches /cart_x_\d_\d/, assign new value; else add a new session variable. Alternately, why don't you store them like $_SESSION["cart"]["b"][1][1]?
    – Salman A
    Jun 13, 2012 at 20:38

3 Answers 3

2

You should consider taking advantange of the awesomeness of what associative arrays let you do:

$_SESSION['categories'][$mycat] = array($user_id, $product_id);

That way whenever you set a new category it overrides the last one. Not sure why you need the user_id at that level, assuming the whole cart belongs to one user, my Session would look like:

array(
    'user' => $user_id,
    'cart' => array('catid' => 'prodid', 'catid2', 'prodid2'))
);
1
  • thanks for your comment, how do i select $user_id in the $mycat array in $_SESSION['categories'][$mycat] = array($user_id, $product_id) ? Jun 13, 2012 at 21:02
2

You should use 3 variables instead of 1.

$_SESSION['category'] = 'cart_b';
$_SESSION['user_id'] = 1;
$_SESSION['product_id'] = 1;

But just in general - you can convert string to a array with '_' separator.

$varArray = explode('_', $_SESSION['var']);
1
  • missing a single quote at line 1
    – Gntem
    Jun 13, 2012 at 20:41
0

explode the session variable using _ and check the first element to find the category.

$myarray=explode("_",$_SESSION['yourvariablename']);

then you the $myarray[1] is the category so you can compare and do other stuff.

Is this what you wanted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.