0

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?

1 Answer 1

1

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);
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your time. Please see stackoverflow.com/questions/58528052/… @Arleigh Hix

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.