views:

130

answers:

5

In PHP, is the following logic allowed

If (x && y)
  //Do A
Elseif (x)
  // Do B
Elseif (y)
  // Do C
Else
  // Do D

Basically, are you allowed to use more than one elseif?

+1  A: 

yup

if(this == this && this == this){
   //this and that
}else if(this == that || this == that){
  //this or that
}else{
  //anything else
}
kilrizzy
don't forget your $ and ==
Moak
I'll also point out that you're using an assignment operator (=) and not a comparison check (==).
David Thomas
AHhhhhhhhhhhhhhh :(
kilrizzy
+10  A: 

Yes:

if ($x && $y) {
  //Do A
} else if ($x) {
  // Do B
} else if ($y) {
  // Do C
} else {
  // Do D
}

Another format useful for HTML files

<?php if ($x && $y): ?>
  Element A
<?php elseif ($x): ?>
  Element B
<?php elseif ($y): ?>
  Element C
<?php else: ?>
  Element D
<?php endif;?>
gnarf
The space between else and if is not necessary in PHP - there is an elseif control statement.
Shadow
tomato / tomatoe ;) just more used to writing `else if`
gnarf
+1 for actually spending time replying to this question
Alec Smart
i figured if someone ever googled PHP conditional else - they might want to find a good answer ;)
gnarf
A: 

Yes, although if the test is simple ($a == $b), use a switch instead:

switch ($a) {
    case $b:
        break;
    case $c:
        break;
    default:
        //Like else
    }
Shadow
+1  A: 

Yes. Please see http://us3.php.net/elseif and http://us3.php.net/elseif.

David Thomas
+1  A: 

You can use

if($x)
    // for one line of code
elseif($y)
    // also for one line of code

if($x) {
    // for more than
    // one line of code
} elseif($y) {
    // also for multi-
    // line codes
}

and

if($x):
    // multi-line
endif;
Tom