首页 > 解决方案 > 值不等于折扣代码的文本框条目

问题描述

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

    $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;
    }

标签: php

解决方案


一开始,您已经将$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'])) {
...
}

推荐阅读