【问题标题】:PHP $_SESSION undefined offsetPHP $_SESSION 未定义的偏移量
【发布时间】:2012-04-05 04:14:06
【问题描述】:

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

【问题讨论】:

    标签: php session undefined offset cart


    【解决方案1】:

    改变这个:

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

    到:

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

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

    【讨论】:

    • @user1274699 Remove 也可以使用 isset。如果未设置,if(!isset($_SESSION['cart'][$p_id])) break; 之类的东西会导致它退出 switch 语句(因为没有什么可删除的)。您可能需要添加额外的错误处理
    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多