Reputation: 1447
Please how do i increment the value of a particular key in an associative array?
I doing the below but it seems not to work. Thank you.
$_SESSION['cart_items'] = ["a" => 1, "b" => 1];
$product_id can be a or b.
foreach ($_SESSION['cart_items'] AS $id => $quantity){
if ($id == $product_id){
$_SESSION[$product_id][$quantity] +=1;
}
}
Upvotes: 1
Views: 2832
Reputation: 116
Or you can also do:
$_SESSION[$product_id] = parseInt($quantity) + 1;
Upvotes: 0
Reputation: 7302
Well you can test the code:
<?php
// start the session and avoid notice
@session_start();
// if not set session for cart_items, set first
if ( ! isset($_SESSION['cart_items'])) {
// this is session data with product details
$_SESSION['cart_items'] = array("a" => 1, "b" => 1);
}
// assuming if product is 'a'
$product_id = $_GET['product_name'];
// check if product 'a' exist in SESSION as KEY then add +1
if (isset($_SESSION['cart_items'][$product_id])) {
$_SESSION['cart_items'][$product_id]++;
}
// debug value of SESSION
echo '<pre>', print_r($_SESSION, true), '</pre>';
// run this code after save in file e.g. test.php?product_name=a or text.php?product_name=b
?>
Upvotes: 2