PHP检查多个条件是否为真

时间:2015-11-29 20:32:54

标签: php

我想要一份声明,检查你的黄金和你的铁是否都大于500,如果其中一个失败,你就无法执行。

现在我还想检查哪一个失败了,所以我可以告诉用户他/她缺少哪种资源。

我不知道什么是解决我的问题的最佳方法,我已经尝试嵌套多个if / elseif但最终是一个大混乱,最重要的是它根本不起作用。

5 个答案:

答案 0 :(得分:0)

我更喜欢以这种方式使用Switch方法:

switch($type){
    case 'gold':
      $sss = 'aaa';
      break;
}

或使用If功能:

if($type == 'gold'){

}else if($type == 'iron'){

}

答案 1 :(得分:0)

您不需要嵌套的if语句。

bool condition1 = gold < 500;
bool condition2 = silver < 1000;
bool condition3 = diamonds < 50;

if (!condition1)
{
    echo "condition 1 failed.";
}
if (!condition2)
{
    echo "condition 2 failed.";
}
if (!condition3)
{
    echo "condition 3 failed.";
}

if (condition1 && condition2 && condition3)
{
    echo "sucess!";
}

如果最终条件太长,您可以始终定义bool failed并在满足上述任何条件时将其设置为true。

答案 2 :(得分:0)

由于您没有提供任何代码,因此要告诉您哪些内容最佳,哪些代码与您的代码相匹配并不容易。一般来说,你可以这样做:

if($amountGold >= 500 && $amountIron >= 500)
{
    //Do funny stuff -> Success
}
else
{
    if($amountGold >= 500)
    {
        echo "Not enough Iron";
    }
    else
    {
        if($amountIron >= 500)
        {
            echo "Not enough Gold";
        }
        else
        {
            echo "Not enough Gold and Iron";
        }
    }
}

答案 3 :(得分:-1)

试试这个:

<?php
$gold=10;
$iron=10;

$failures=array();
if ( $gold >= 500 && $iron >= 500 )
{
    /*
     * Success
     */
} else
{
    if ( $gold < 500 )
    {
        $failures[] = 'Gold';
    }

    if ( $iron < 500 )
    {
        $failures[] = 'Iron';
    }
}

echo ((count($failures)>0) ? implode (', ',$failures)." failed" : "Huzzah!").PHP_EOL;

答案 4 :(得分:-2)

进行以下检查:

x
相关问题