1

Friends, I appreciate any comments.

I'm having problems with array_key_exists. I need to check if a product already exists in the shopping cart. I'm doing it this way:

.
$session = $this->request->getSession();
            $cart = $session->read( 'cart' );
            
            if (array_key_exists($order->product_id, (array) $cart)) {
                $this->Flash->error('Invalid request');

            } else {
                $cart[] = $order;
                $session->write('cart', $cart );
                $this->Flash->success($order->product->name_product . ' has been added to the shopping cart');
                return $this->redirect( ['action' => 'index'] );

            }
            return $this->redirect($this->referer());
        } else {
            return $this->redirect(['action' => 'index']);
        }
.
.

I received the error below, but now with the update it no longer exists. But the function still doesn't help me.

array_key_exists() expects parameter 2 to be array, int given

The product is added to the cart even if it has already been added. I need to compare the selected product id with the product id that is already in the cart. The order information is basically: id, quantity, user_id, product_id.

I am grateful if anyone can analyze some way to check the id in the array that is mounted.

3
  • array_key_exists ( mixed $key , array $array ) : bool - i.e. turn around your params: if (array_key_exists($order->product_id, (array) $cart)) { Commented Jul 7, 2020 at 21:34
  • Thank you. The error is gone, but the if doesn't work. No error, just let the registration pass even the product already exists in the cart. Can you tell me if the array_key_exists () function is for that? debug ($ session-> read ('cart')); shows 'product_id' => (int) 31, 'quantity' => (int) 1, ... Commented Jul 7, 2020 at 23:01
  • The data you've provided doesn't match your code. Are you sure it's not saying something more like Array( 0 => Array('product_id' => (int) 31, ...? Commented Jul 8, 2020 at 1:40

1 Answer 1

1

When you do this:

$cart[] = $order;

you are asking PHP to add a new element to the end of your $cart array, giving it the next available numeric key. You are then trying to see if the product id exists as a key in the array. Unless your product ids are like 0 and 1, that's unlikely to ever happen. If you want your cart to be keyed by product id, use

$cart[$order->product_id] = $order;
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.