ragrim Posted February 20, 2012 Share Posted February 20, 2012 Hi, Im encountering this error when i add items to my cart, im using sessions to store my cart items in an array. this error only happens the first time i add something, then if i go clear my session it works and no errors. Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in /home/byronhea/public_html/oos/mini-cart.php on line 18 Here is the line its refering to if(array_key_exists($pid, $_SESSION['cart'])) and here is the block of code it belongs to if(!isset($_SESSION)) { session_start('cart'); } // Process actions $pid = $_POST['prodid']; $q = $_POST['qty']; if(array_key_exists($pid, $_SESSION['cart'])) { $_SESSION['cart'][$pid]=$_SESSION['cart'][$pid]+$q; } ELSE { $_SESSION['cart'][$pid]=$q; } Any help would be appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/257363-array_key_exists-error/ Share on other sites More sharing options...
psynor Posted February 20, 2012 Share Posted February 20, 2012 Can you var_dump your $_SESSION['cart'] Quote Link to comment https://forums.phpfreaks.com/topic/257363-array_key_exists-error/#findComment-1319151 Share on other sites More sharing options...
ragrim Posted February 20, 2012 Author Share Posted February 20, 2012 i made a change to my code and have not recieved any errors as yet, but its hard to tell if i fixed it as this error is random and doesnt happen all the time. i changed it to if(isset($_SESSION['cart'][$pid])) { $_SESSION['cart'][$pid]=$_SESSION['cart'][$pid]+$q; } else { $_SESSION['cart'][$pid]=$q; } I was reading in the php manual that using isset may not be the right way to go about this but its the only way i could avoid the error as any other way seems to produce random errors. Any help would be appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/257363-array_key_exists-error/#findComment-1319333 Share on other sites More sharing options...
xyph Posted February 20, 2012 Share Posted February 20, 2012 You have to check if the key exists and contains an array before using array_key_exists() Alternately, you can simply use isset() if( isset($_SESSION['cart'][$pid] ) { // etc. } This won't result in an error if ['cart'] doesn't exist, and is actually faster than array_key_exists() Quote Link to comment https://forums.phpfreaks.com/topic/257363-array_key_exists-error/#findComment-1319337 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.