0

我有多个条件的 if 语句,
这两个条件有什么区别:
1。

    if($province=="AB" || "NT" || "NU" || "YT")
{
    $GST=5;
}
else if($province=="BC" || "MB")
{
    $GST=5;
    $PST=7;
}
else if($province=="NB" || "NF" || "ON")
{
    $HST=13;
}  

第二个是:
2。

if($province=="AB" || $province=="NT" || $province=="NU" || $province=="YT")
{
    $GST=5;
}
else if($province=="BC" || $province=="MB")
{
    $GST=5;
    $PST=7;
}
else if($province=="NB" || $province=="NF" || $province=="ON")
{
    $HST=13;
}
4

3 回答 3

3

两者的区别在于第一个不能按预期工作,而第二个在技术上是正确的。

编码:

if($province=="AB" || "NT" || "NU" || "YT")

将始终评估为真并执行该条件块中的代码。

原因是你只检查 if$province == "AB"然后你检查 if "NT" == truewhich 将评估为 true。

要根据所有这些值(AB、NT、NU、YT)检查省份,您需要明确检查$province每个值,而不仅仅是第一个值,这是您在第二个示例中正确执行的操作。

于 2012-08-05T03:51:15.703 回答
2

I add to drew010 answer that you can do this too (wich is simpler) :

if(in_array($province,array("AB","NT","NU","YT"))
{
    $GST=5;
}
else if(in_array($province,array("BC","MB"))
{
    $GST=5;
    $PST=7;
}
else if(in_array($province,array("NB","NF","ON"))
{
    $HST=13;
}
于 2012-08-05T03:53:58.053 回答
1

The first one will always evaluate to true. In the second, third, and forth OR clauses in the first example you are basically asking PHP to convert the strings to Boolean values, and non-empty strings will always evaluate as true.

Just for fun, my favorite way to handle conditionals like this is with a switch statement. It's a lot easier for me to read, but it's really a personal preference thing.

switch ( $province ) {

   case 'AB' :
   case 'NT' :
   case 'NU' :
   case 'YT' :

     $GST = 5;

   break;

   case 'BC' :
   case 'MB' :

     $GST = 5;
     $PST = 7;

   break;

   case 'NB' :
   case 'NF' :
   case 'ON' :

      $HST = 13;

   break;

}
于 2012-08-05T03:52:28.273 回答