PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 31, 2021

[FIXED] array_key_exists() expects parameter 2 to be array, null given - Cakephp 3

 December 31, 2021     array-key-exists, cakephp, cakephp-3.0, php     No comments   

Issue

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.


Solution

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;


Answered By - Greg Schmidt
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing