我用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。如果i删除了第1和第2条语句,则它可以正常工作。
如果Y
或M
存在,则第一条和第二条语句将始终为真,并且脚本不会进一步检查后面的语句,因此,如果您想在语句中使用两个变量,则需要在两个条件下都使用
if(($ids_fetch["s_type"]=="Y") && ($ids_fetch["register"] != "R"))
第二个也一样,应该是
else if($ids_fetch["s_type"]=="M") && ($ids_fetch["register"] !="R"))
在这段代码中,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;
}
?>
从你的代码中,第三和第四个条件将永远不会执行。
对于If/Else If/Else语句,只执行其中一个。这是因为一旦达到一个条件,该块将被执行,而其余的将不被计算。如果没有条件为真,则执行else将阻塞。
你的第一条件($ids_fetch["s_type"] == "Y")
和你的第三条件($ids_fetch["s_type"] == "Y" && $ids_fetch["register"] == "R")
是接近的,但不相同。如果要满足第三个条件,那么第一个条件就必须为真。因此,它将被求值并执行,而第三条将被跳过。
第二种情况和第四种情况也是如此。
我建议把第三和第四作为第一和第二,你的逻辑应该工作。
<?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";
}
?>