PHP $ _SESSION未定义的偏移量

时间:2012-04-05 04:14:07

标签: php session undefined offset cart

当我执行以下代码时,例如: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;
}
}
?>

我收到以下错误:

Notice: Undefined offset: 1 in cart.php on line 11

如何核心配置PHP $ _SESSION?我

1 个答案:

答案 0 :(得分:3)

改变这个:

$_SESSION['cart'][$p_id]++

为:

$_SESSION['cart'][$p_id] = 1 + (isset($_SESSION['cart'][$p_id]) ? $_SESSION['cart'][$p_id] : 0);

这样您就不会尝试增加数组中不存在的元素。