PHP未定义索引 - 使用isset()switch语句

时间:2013-03-28 21:05:54

标签: php arrays

我知道这个问题有很多帖子。我看过很多帖子,但出于某种原因,我似乎找到了答案!

非常感谢任何帮助。我对PHP很新,所以如果我说错了,我会道歉。

我正在尝试使用数组创建一个基本的篮子系统。我一直在$_SESSION['cart'][$app_ID]++;行上得到一个错误未定义的索引。有趣的是它的所有功能都正确!我想解决错误,而不仅仅是关闭错误报告。

    if(isset($_GET['id'])){


$app_ID = $_GET['id'];   //the item id from the URL 
$action = $_GET['action']; //the action from the URL 


$total = 0;


if (isset($app_ID)){

switch($action) {       

    case "add":
        $_SESSION['cart'][$app_ID]++;
    break;

    case "remove":
        $_SESSION['cart'][$app_ID]--; 
        if($_SESSION['cart'][$app_ID] == 0) unset($_SESSION['cart'][$app_ID]); 
    break;

    case "empty":
        unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
    break;

谢谢你们和女孩们。

4 个答案:

答案 0 :(得分:0)

要使用$ _SESSION,您必须先发送session_start(),然后再发送任何标题信息

我希望这能帮到你,

干杯,

答案 1 :(得分:0)

session_start(); // at the top

case "add":
    if (isset( $_SESSION['cart'][$app_ID] )){
        $_SESSION['cart'][$app_ID]++;
    } else {
        $_SESSION['cart'][$app_ID] = 1;
    }
break;

答案 2 :(得分:0)

值得一提的是,它只是一个通知,而不是一个错误。您基本上必须检查数组索引是否存在并在引用它之前对其进行初始化。

if (isset($app_ID)) {
    switch($action) {       

        case "add":
            if (!isset($_SESSION['cart']) {
                $_SESSION['cart'] = array();
            }

            if (!isset($_SESSION['cart'][$app_ID]) {
                $_SESSION['cart'][$app_ID] = 0;
            }

            $_SESSION['cart'][$app_ID]++;
        break;

        case "remove":
            if (isset($_SESSION['cart'] && isset($_SESSION['cart'][$app_ID]) {
                $_SESSION['cart'][$app_ID]--; 
                if ($_SESSION['cart'][$app_ID] <= 0) {
                   unset($_SESSION['cart'][$app_ID]);
                }
            }
        break;

        case "empty":
            unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
        break;
    }
}

为了安全起见,我还将== 0中的remove更改为<= 0

答案 3 :(得分:0)

您应该在任何地方使用isset($_SESSION['cart'][$app_ID])isset( $_SESSION['cart'])

通常,在引用它之前,必须确保存在和数组索引。您可以使用isset()执行此操作,也可以在不可避免的情况下编写代码(例如,在某处添加索引)。

我想,问题的另一部分是您的代码有效的原因。解释很简单。当您引用不存在的索引时,会发出您观察到的通知(在非生产环境中)但不会停止该程序。由于没有任何东西可以使用,因此为该数组值返回null。因此,该值假定为null,并且++将值作为整数,并将null转换为整数0,然后将其提高一。由于++是一个写入的运算符,它将为您创建数组项。由于$a++被定义为$a=$a+1,因此很容易看出您所写的内容为$_SESSION['cart'][$app_ID]=$_SESSION['cart'][$app_ID]+1,而$_SESSION['cart'][$app_ID]=null+1 null+1执行0+1 {{1}} 1}}产生0,因此0被分配给(以前缺少的)数组项。希望这有助于看清楚。 ;)