【问题标题】:Run code only if IF and ELSEIF Statement Run仅在 IF 和 ELSEIF 语句运行时运行代码
【发布时间】:2016-06-14 03:53:53
【问题描述】:
$Variable = "Dog"

if($Variable == "Cat"){
     do stuff
}
elseif($Variable == "Goat"){
     do other stuff
}
elseif($Variable == "Cash"){
     Run some other stuff
}

我将如何编写代码来表示 当且仅当其中一个陈述为真时才回显“hi”? 我的问题是我必须在每个语句中写 echo "hi" 吗?或者我可以通过某种方式来节省线条吗?

【问题讨论】:

  • 1) 你知道= 是赋值而不是比较?! 2) 要么编写一个 if 语句,通过 OR 运算符组合所有条件,要么将其放入每个 if 语句中。
  • 欺骗是针对 JS 的,但对于 PHP 也是如此。
  • @MarcB 骗子是针对 PHP 的 ;),它可能只是被标记为 JS,因为它几乎相同。我认为 OP 只是想在他拥有的 3 个条件之一为真时输出一些东西(但问题的主体和标题有点争议)。
  • @CodingMageSheen 正如我所说,要么编写一个 if 语句,将所有条件与 OR 运算符结合起来,要么将其放入每个 if 正文中。
  • 如果要执行相同的代码,可以编写多个条件。如果动物是狗或猫,if ($animal == "cat" || $animal == "dog") { save(); } 会这样做。

标签: php if-statement conditional-statements


【解决方案1】:

对此没有特殊的控制结构,但是有几种方法可以实现这一点,而不必写三遍echo 'hi';。这部分是品味问题,部分是实际情况的问题。例如,如果您只是说“嗨”,那一切都无关紧要,但是如果您想做一些复杂的事情,那就是另一回事了。一些建议:

1.再写一个 if/else 子句

if ( $variable == "Cat" || $variable == "Dog" || $variable == "Goat" ) {
    echo 'hi!';
}

2。使用 else 排除

$say_hi = true;

if( $Variable == "Cat" ){
    // do stuff
} else if( $Variable == "Dog" ){
    // do other stuff
} else if( $Variable == "Goat" ){
    // do whatherever
} else {
    $say_hi = false;
}

if ( $say_hi ) {
    echo 'hi';
}

3.使用函数

这确实取决于您的用例,但它可能是可行的。

function feed( $animal ) {
    if ( $animal == 'cat' ) {
        // feed the cat
        return true;
    } else if ( $animal == 'dog' ) {
        // feed the dog;
        return true;
    } else if ( $animal == 'goat' ) {
        // feed the goat
        return true;
    }
    return false;
}

if ( feed('dog') ) {
    echo 'hi';
}

if ( feed('cat') ) {
    echo 'hi again';
}

4.使用数组

这也取决于您的用例,但也很方便

function cat_function() {
    echo 'The cat says meaauw';
}

function dog_function() {
    // etc
}

function goat_function() {
    // you got the point
}

$animals = array(
    'cat'  => 'cat_function', 
    'dog'  => 'dog_function', 
    'goat' => 'goat_function'
);

$my_pet = 'dog';

if ( array_key_exists( $my_pet, $animals ) ) {
    call_user_func( $animals[ $my_pet ] );
}

好的,我可以想到其他一些,但我需要你的用例;)

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    相关资源
    最近更新 更多