Reputation: 785
When I execute this following code for example: cart.php?p=1&action=add
<?php
session_start();
if (isset($_GET['p']) && isset($_GET['action'])) {
$p_id = (int)$_GET['p'];
$action = $_GET['action'];
switch($action) {
case "add":
$_SESSION['cart'][$p_id]++;
echo $_SESSION['cart'][$p_id];//for debug
break;
case "remove":
$_SESSION['cart'][$p_id]--;
echo $_SESSION['cart'][$p_id];
if($_SESSION['cart'][$p_id] == 0) unset($_SESSION['cart'][$p_id]);
break;
case "empty":
unset($_SESSION['cart']);
break;
}
}
?>
I get the following error:
Notice: Undefined offset: 1 in cart.php on line 11
How can i configure the PHP $_SESSION corectly? I
Upvotes: 0
Views: 1690
Reputation: 141827
Change this:
$_SESSION['cart'][$p_id]++
to:
$_SESSION['cart'][$p_id] = 1 + (isset($_SESSION['cart'][$p_id]) ? $_SESSION['cart'][$p_id] : 0);
So that you don't try to increment a non existent element in your array.
Upvotes: 3