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.
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;