0

I am trying to increase quantity of a product when the id of that product already exists inside an array.

My product array $arr2 looks like this for example:

Array
(
    [productid] => 3
    [productname] => Eikenhout pallet
    [productalias] => eikenhout-pallet
    [productcat] => Eikenhout
    [catalias] => eikenhout
    [quantity] => 1
    [kuubkosten] => 150|1 kuub
)

Then I create a session and add all information to it.

if (!isset($_SESSION['cart'])) {
     // and turn session into array
   $_SESSION['producten'] = array();
}

// If id of product does not exist, add it to session
if(!isset($_SESSION['producten'][$arr2['productid']])){
    $_SESSION['producten'][$arr2['productid']] = $arr2;
// Else add to quantity
}else{
    $_SESSION['producten'][$arr2['productid']]['quantity'] += $arr2['quantity'];
}

If I then print my session, this is what I get:

Array
(
    [3] => Array
        (
            [productid] => 3
            [productname] => Eikenhout pallet
            [productalias] => eikenhout-pallet
            [productcat] => Eikenhout
            [catalias] => eikenhout
            [quantity] => 1
            [kuubkosten] => 150|1 kuub
        )

)

But after adding the product again, the quantity is not increased. What am I doing wrong? I can see in my network tab that all data is correctly posted and there are no errors.

11
  • += $arr2['quantity'] should be $arr2['quantity']+1; maybe Commented Feb 4, 2019 at 15:44
  • @devpro But what if in the future I want customers to be able to add any quantity at once? For example add 10 products in one click? Commented Feb 4, 2019 at 15:46
  • @devpro += is an acceptable operator in PHP.. Commented Feb 4, 2019 at 15:46
  • If you are truely doing this $_SESSION['producten'][$arr2['productid']] = $arr2; then WHERE in the session array is producten Commented Feb 4, 2019 at 15:46
  • @RiggsFolly That is the name of my session. Printing $_SESSION['producten'] shows me the second array in my question. Commented Feb 4, 2019 at 15:48

1 Answer 1

1

As devpro already said, you are checking if the key 'cart' isset

if (!isset($_SESSION['cart'])) {

But you are never setting that variable. Your code might just work when you change

if (!isset($_SESSION['cart'])) {
    // and turn session into array
    $_SESSION['producten'] = array();
}

to

if (!isset($_SESSION['producten'])) {
    // and turn session into array
    $_SESSION['producten'] = array();
}
Sign up to request clarification or add additional context in comments.

Comments

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.