迭代数组时出错

时间:2011-04-20 12:29:19

标签: php arrays if-statement

嘿伙计们试图通过一系列复选框来累加价格并不断出现意外}错误,我无法弄清楚原因:

            $price;
        foreach($_POST['extras'] as $extra)
            {
            if($extra == "Deodoriser"){
                        $price = $price + 10;
                    } elseif($extra == "Carpet Protector (5 litre)"){
                        $price = $price + 20
                    } elseif($extra == "Carpet Repair Tools"){
                        $price = $price + 30
                    } elseif($extra == "Furniture Moving Equipment"){
                        $price = $price + 40
                    } elseif($extra == "Furniture Tabs"){
                        $price = $price + 50
                    } elseif($extra == "Urine Decontamination Treatment"){
                        $price = $price + 60 }
            }

我现在收到此错误 解析错误:语法错误,第45行/home/fevsdiet/public_html/diycarpetcare.co.uk/booking/booking.event.processing.php中的意外T_FOREACH

1 个答案:

答案 0 :(得分:0)

if($extra == "Deodoriser"){ 
    $price = $price + 10; 
} elseif($extra == "Carpet Protector (5 litre)") { 
    $price = $price + 20; 
} elseif($extra == "Carpet Repair Tools") { 
    $price = $price + 30; 
} elseif($extra == "Furniture Moving Equipment") {
    $price = $price + 40; 
} elseif($extra == "Furniture Tabs") {
    $price = $price + 50;
} elseif($extra == "Urine Decontamination Treatment") {
    $price = $price + 60;
} else {
    $price = 0;
}

替代:

foreach($_POST['extras'] as $extra) {
    switch($extra) {
        case 'Deodoriser':
            $price = $price + 10;
            break;
        case 'Carpet Protector (5 litre)':
            $price = $price + 20;
            break;
        case 'Carpet Repair Tools':
            $price = $price + 30;
            break;
        case 'Furniture Moving Equipment':
            $price = $price + 40;
            break;
        case 'Furniture Tabs':
            $price = $price + 50;
            break;
        case 'Urine Decontamination Treatment':
            $price = $price + 60;
            break;
        // Could add a default as well
        default:
            $price = 0;
    }
}