user4271704
user4271704

Reputation: 763

How to increment the session array value?

I am using this on a shopping cart

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    $data[] = $_getvars['id'];
    $session->set('cart', $data);
} 

$_getvars['id'] is productid, and on each click, a new array element will be added to the session. It works fine as it is now, but if a product is chosen more than once a new array will be added, how can change it that productid will be array offset and the value will be incremented from 1 each time to reflect the quantity?

$i = 1;
if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    $data[$_getvars['id']] = $i++;
    $session->set('cart', $data);
} 

but this code each time resets to 1. How to fix it? Or any better array structure for a shopping cart?

Upvotes: 0

Views: 187

Answers (1)

Arleigh Hix
Arleigh Hix

Reputation: 10897

If it's not set, set it to zero, then always add one.

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    if(!isset($data[$_getvars['id']]){
        $data[$_getvars['id']] = 0;
    }
    $data[$_getvars['id']] += 1;
    $session->set('cart', $data);
} 

Or you could add a dynamic quantity

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    if(!isset($data[$_getvars['id']]){
        $data[$_getvars['id']] = 0;
    }
    // $_GET['qty'] OR 1, if not set
    $qty = (!empty($_getvars['qty']))? $_getvars['qty']: 1;
    $data[$_getvars['id']] += $qty;
    $session->set('cart', $data);
} 

Upvotes: 1

Related Questions