if else语句不完全正常工作

时间:2013-05-15 15:00:25

标签: php if-statement

我用else if语句编写了一个代码,但它的工作方式并不完全正常。

代码:

<?php
if($ids_fetch["s_type"]=="Y")
{
    echo "Yearly";
}
else if($ids_fetch["s_type"]=="M")
{
    echo "Monthly";
}
else if($ids_fetch["s_type"]=="Y" && $ids_fetch["register"]=="R")
{
    echo "Ref-Yearly";
}
else if($ids_fetch["s_type"]=="M" && $ids_fetch["register"]=="R")
{
    echo "Ref-Monthly";
}
else
{
    echo "Free";
}
  ?>

它唯一的回音1,2,5声明但不是3,4。如果我删除了1和2声明,那么它的效果非常好。

3 个答案:

答案 0 :(得分:1)

如果YM出现并且脚本不会进一步检查以后的状态,那么您的第一和第二个陈述将是真的,因此如果您想在您的陈述中使用两个变量你需要在两种情况下使用

if(($ids_fetch["s_type"]=="Y") && ($ids_fetch["register"] != "R"))

第二个应该是

else if($ids_fetch["s_type"]=="M")  && ($ids_fetch["register"] !="R"))

答案 1 :(得分:1)

在这段代码中,3和4永远不会成真。如果$ids_fetch["s_type"]=="Y"为真,则它永远不会评估3是否为真。

2和4也是如此。您可以通过重新排序来修复它:

<?php
if($ids_fetch["s_type"]=="Y" && $ids_fetch["register"]=="R")
{
    echo "Ref-Yearly";
}
else if($ids_fetch["s_type"]=="M" && $ids_fetch["register"]=="R")
{
    echo "Ref-Monthly";
} 
else if($ids_fetch["s_type"]=="Y")
{
    echo "Yearly";
}
else if($ids_fetch["s_type"]=="M")
{
    echo "Monthly";
}
else
{
    echo "Free";
}
?>

或者最好使用switch语句

<?php
switch($ids_fetch['s_type'])
{
    case 'Y':
    if($ids_fetch["register"]=="R")
    {
        echo "Ref-Yearly";
    } else {
        echo "Yearly";
    }
    break;

    case 'M':
    if($ids_fetch["register"]=="R")
    {
        echo "Ref-Monthly";
    } else {
        echo "Monthly";
    }
    break;

    default:
    echo "free";
    break;
}
?>

答案 2 :(得分:0)

从您的代码中,第3和第4个条件永远不会执行。

使用If / Else If / Else语句,只会执行其中一个语句。这是因为一旦达到一个条件,将执行该块,并且不会评估其余块。如果没有条件成立,那么将执行else将阻止。

您的第一个条件($ids_fetch["s_type"] == "Y")和您的第三个条件($ids_fetch["s_type"] == "Y" && $ids_fetch["register"] == "R")很接近,但不一样。如果要满足第三个条件,那么第一个条件必然是真的。因此,它将被评估和执行,并且将跳过第3个。

第二个条件和第四个条件也一样。

我建议将第3和第4作为第1和第2,你的逻辑应该有效。

<?php
if($ids_fetch["s_type"]=="Y" && $ids_fetch["register"]=="R")
{
    echo "Ref-Yearly";
}
else if($ids_fetch["s_type"]=="M" && $ids_fetch["register"]=="R")
{
    echo "Ref-Monthly";
}
else if($ids_fetch["s_type"]=="Y")
{
    echo "Yearly";
}
else if($ids_fetch["s_type"]=="M")
{
    echo "Monthly";
}

else
{
    echo "Free";
}
  ?>