是否可以在同一个 if 块中运行多个 elseif 块


Is it possible to run multiple elseif blocks in the same if block?

$foo=1;
function someFunction(){
  if($foo==0){ //-------Will test, won't execute
    bar();
  }elseif($foo==1){ //--Will test, and execute
    baz();
  }elseif($foo==2){ //--Doesn't test
    qux();
  }elseif($foo==3){ //--Doesn't test
    quux();
  }else{ //-------------Doesn't test
    death();
  } //------------------The program will skip down to here.
}

假设 baz(( 更改了 $foo 的值,并且每次都不同。我希望我的代码在第一个语句之后继续测试 elseif/else 语句,如果它们是真的,则运行这些语句。

我不想再次运行整个函数(即我不在乎 $foo = 0 还是 1(。我正在寻找类似"继续;"的东西。无论如何,如果这可能,请告诉我。谢谢。:)

编辑**我的代码实际上比这复杂得多。我只是为了理论而写下一些代码。我想要的只是脚本在通常不会的地方继续测试。

如果我理解正确,您希望执行每个连续的elseif,无论前if/elseif是否匹配,但是如果if/elseif都不匹配,您还希望运行一些代码。在这种情况下,您可以将标志$matched设置为true,如果其中一个匹配,则改用if

<?php
$foo=1;
function someFunction(){
  $matched = false;
  if($foo==0){
    bar();
    $matched = true;
  }
  if($foo==1){ //--This elseif will get executed, and after it's executed,
    baz();
    $matched = true;
  }
  if($foo==2){
    qux();
    $matched = true;
  }
  if($foo==3){
    quux();
    $matched = true;
  }
  if(!$matched){ /* Only run if nothing matched */
    death();
  }
}

如果您还希望能够跳到最后,请使用goto(但请先查看以下内容(:

<?php
$foo=1;
function someFunction(){
  $matched = false;
  if($foo==0){
    bar();
    $matched = true;
    goto end: // Skip to end
  }
  if($foo==1){ //--This elseif will get executed, and after it's executed,
    baz();
    $matched = true;
  }
  if($foo==2){
    qux();
    $matched = true;
  }
  if($foo==3){
    quux();
    $matched = true;
  }
  if(!$matched){ /* Only run if nothing matched */
    death();
  }
  end:
}
我不知道

这是否是你的意思,但你可以使用 switch 语句:

$foo=1;
function someFunction(){
  switch($foo==0){
    case 0:
        bar();
    case 1:
        baz();
    case 2:
        qux();
    case 3:
        quux();
    default:
        death();
}

请注意,不是每个案例的中断。

你不能使用else if ,只是一堆如果......

//此响应不正确。请参阅下面的评论。谢谢!

不是专家,但据我了解,它们将继续运行。如果将来您正在编写一组elseif()语句,并且想要在其中一个语句为真时离开序列,请使用 break 命令。 另请参阅switch()

如果我错了,我绝对愿意纠正。