shekwo
shekwo

Reputation: 1447

Incrementing the value of one associative array key

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

Answers (3)

kiong
kiong

Reputation: 116

Or you can also do:

$_SESSION[$product_id] = parseInt($quantity) + 1;

Upvotes: 0

Nono
Nono

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

Pipe
Pipe

Reputation: 2424

Just do

$_SESSION['cart_items'][$product_id]++;

Upvotes: 3

Related Questions