值不等于折扣代码的文本框条目

时间:2019-04-06 01:45:22

标签: php

我正在尝试使用一个可以正常工作的简单折扣代码,但是当输入错误代码时,我想显示一条错误消息。到目前为止,我已经解决了这个问题,但是消息始终显示,而不是仅在输入错误代码时显示。

    $discount = ( int )$_GET[ 'discount' ];;
    $codes = array(10, 20);

    if ($discount == "10"){
        $discount_total = round($grand_total * ((100-10) / 100), 2);;
        $message = "Discount Code '" . $discount . "' has been successfully applied.";
    }elseif (!in_array(intval($discount), $codes, true)){
        $message = "Sorry, this code is not valid.";
        $discount_total = $grand_total;
    }else {
        $discount_total = $grand_total;
    }

1 个答案:

答案 0 :(得分:2)

一开始,您已经将$discount变量转换为int类型:

$discount = ( int )$_GET[ 'discount' ];

只需信任您的代码即可。

$codes = array(10, 20);
// if ($discount == "10") { <--- this is bad, you compare your int value with string "10"
if ($discount === 10) { // <-- this is clear code
    $discount_total = round($grand_total * ((100-10) / 100), 2);;
    $message = "Discount Code '" . $discount . "' has been successfully applied.";
// } elseif (!in_array(intval($discount), $codes, true)){ <-- same mistake here, we dont need to cast $discount again
} elseif (!in_array($discount, $codes)) { // <-- this should just work fine, the only question: if you already checked value 10, why not just to check 20? why do you check against array of 2 values?
    $message = "Sorry, this code is not valid.";
    $discount_total = $grand_total;
} else {
    $discount_total = $grand_total;
}

更新:如果要检查是否已发送GET参数,则可以使用以下方法包装所有片段:

if (isset($_GET['discount'])) {
...
}