Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
}

Let's say that baz() changes the value of $foo and it is different every time. I want my code to keep testing the elseif/else statements after the first one and run those if they are true.

I don't want to run the whole function again, (i.e. I don't care if $foo = 0 or 1). I'm looking for something like "continue;". Anyways please let me know if this is possible. Thanks. :)

EDIT** My code is actually way more complicated than this. I was just putting some code down for the sake of theory. All I want is the script to keep testing where it usually wouldn't.

like image 943
Aust Avatar asked Dec 28 '22 00:12

Aust


1 Answers

If I'm understanding correctly, you want to do each consecutive elseif, regardless of whether previous if/elseifs matched, but you also want some code to run if none of the if/elseifs match. In this case, you can set a flag $matched to be set to true if one of them matches and use ifs instead.

<?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();
  }
}

If you also want to be able to skip to the end, use goto (but see this first):

<?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:
}
like image 171
0b10011 Avatar answered Dec 29 '22 13:12

0b10011