0

I have question about the SESSION array.

I just add item and qty in different session. I use code like this :

$_SESSION['idproduct'] = $id.",";
$_SESSION['qtyproduct'] = $qty.",";

I have write the condition so the value of session will be like this if we add 3 item :

$_session['idproduct'] = 1,4,6,
$_session['qtyproduct'] = 3,4,5,

my question is how to update quantity if i have get the id ?

user3551629
  • 9
  • 1
  • 6

3 Answers3

0

You could use explode function and push another item into the array

$items = explode($_SESSION['idproduct']);
$items[] = $your_new_value;
print_r($items); // this will you the values inside the array.
$_SESSION['idproduct'] = implode(',', $items);
Mir Adnan
  • 844
  • 11
  • 24
0

Store them as arrays, that way you can access the quantity using the ID as a key:

$_SESSION['quantity'][$id] = $quantity;

So instead of storing your ID and Quantity in two separate strings, you have them in one array, with the ID as the key. Converting your example above your array will look like this:

array(
    1    => 3
    4    => 4
    6    => 5
);

Then if you wanted to add / adjust anything you just set $id and $quantity to the appropriate values and use the line above.

Styphon
  • 10,304
  • 9
  • 52
  • 86
0

The best way to achieve it is to store quantity as a value with product ID as a key, so if you have:

idproduct  = 1,4,6,
qtyproduct = 3,4,5,

Store it as:

$_SESSION['qtyproduct'] = array(
  1 => 3,
  4 => 4,
  6 => 5,
);

Right now if you have a product id:

$id = 4;

You can access quantity with:

$quantity = $_SESSION['qtyproduct'][$id];

and modify it with:

$_SESSION['qtyproduct'][$id] = 7;
hsz
  • 148,279
  • 62
  • 259
  • 315