0

ATM, I'm testing my cart. When I load a new page with products to add to cart, they add add fine but i also get an error of for example:

Notice: Undefined index: cart_25 in

25 IS the index that is associated with the product.

  if (isset($_GET['add'])) {
   $_SESSION['cart_'.(int)$_GET['add']]+=1;
   }


   foreach($_SESSION as $name => $value) {
    if ($value>0){
     if (substr($name,0,5)=='cart_') {
       $name = substr($name, 5, (strlen($name)-5));
       echo $name.'<br />';
     }

Any tips to help would be great

1
  • As one of the answers below indicates, there's no need to cast the $_GET['add'] to an int, when you are going to concatenate it (as a string) to 'cart_' Commented Feb 22, 2012 at 18:01

3 Answers 3

3

try it this way:

$key = 'cart_' . $_GET['add'];
$_SESSION[$key] = isset($_SESSION[$key]) ? $_SESSION[$key] + 1 : 1;
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of using cart_{index} why don't you just make the array multiple dimensions? Then your foreach loop would be a lot simpler. You may also want to have functions or methods for adding and removing items so you don't have to do the same tests every time.

function add_to_cart($index, $amount) {
   if (!isset($_SESSION['cart'][$index])) {
      $_SESSION['cart'][$index] = 0;
   }
   $_SESSION['cart'][$index] += $amount;
}

Comments

0

$_SESSION['cart_'.(int)$_GET['add']]+=1; does $_SESSION['cart_'.(int)$_GET['add']] = **$_SESSION['cart_'.(int)$_GET['add']]** + 1; so first time it will be undefined, so

if (!isset($_SESSION['cart_'.(int)$_GET['add']])) {
    $_SESSION['cart_'.(int)$_GET['add'] = 1;
} else {
    $_SESSION['cart_'.(int)$_GET['add']]+=1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.