syntax error in case 'remove' when decreme

2019-03-06 01:39发布

问题:

I get a syntax error on the case "remove". I've been trying to fix it but I can't figure it out. Can anyone tell me how to fix it?Thanks

The code is for a online shop shopping cart

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

case "remove":
    if (isset($_SESSION['cart'][$id]))
    (
        $_SESSION['cart'][$id]--; (ERROR HERE)
        if ($_SESSION['cart'][$id]==0)
            unset($_SESSION['cart'][$id]);
    )
break;

case "empty":
    unset($_SESSION['cart']);
break;

}

回答1:

You are using parenthesis instead of brackets for your IF statement:

if (isset($_SESSION['cart'][$id]))
( <-- HERE
    $_SESSION['cart'][$id]--; (ERROR HERE)
    if ($_SESSION['cart'][$id]==0)
        unset($_SESSION['cart'][$id]);
) <-- HERE


回答2:

Please replace ( and ) with { and }

Corrected code:

case "remove":
    if (isset($_SESSION['cart'][$id]))
    {
        $_SESSION['cart'][$id]--; (ERROR HERE)
        if ($_SESSION['cart'][$id]==0)
            unset($_SESSION['cart'][$id]);
    }
break;


回答3:

// Syntactical Errors, Find the corrected code!!

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

case "remove":
    if (isset($_SESSION['cart'][$id])) {
            $_SESSION['cart'][$id]--; //(ERROR HERE)
        }
        if ($_SESSION['cart'][$id]==0) {
            unset($_SESSION['cart'][$id]);
        }
    break;

case "empty":
    unset($_SESSION['cart']);
    break;

  }


标签: php case