0

I'm new to cookies here is how i'm setting and retrieving data

if(!isset($_COOKIE['cart'])){
$_COOKIE['cart'] = array();
}

setcookie("cart[$stk_id]['name']", $name, time()+24*60*60, "/");
setcookie("cart[$stk_id]['quantity']", $qty, time()+24*60*60, "/");
setcookie("cart[$stk_id]['vendor']", $vendor, time()+24*60*60, "/");

foreach ($_COOKIE['cart'] as $stk_id => $product){
    $qty = $product['quantity'];
    $pro_name = $product['name'];
} 

but i'm getting error Notice: Undefined index: quantity and name. what is the problem?

nisha
  • 3
  • 3

1 Answers1

0

Cookies array store is commonly used by once variable ,you are set cookies name in array,but create array first and after set cookie name is more convenient.Here you can set by json_encode and json_decode

$data = array($stk_id => 
              array(
                   "name" => $name,
                   "quantity" => $qty,
                   "vendor" => $vendor
                   )
             );
setcookie("cart", json_encode($data), time()+24*60*60, "/");   
$cookie = json_decode($_COOKIE['cart'],true);//for array output

foreach ($cookie as $stk_id => $product){
            $qty = $product['quantity'];
            $pro_name = $product['name'];
} 
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52