PHP elseif statement

Elseif: Between if and Else

 

<?php

if ( conditional expression ) {
  expression
} elseif ( conditional expression ) {
  expression
} else {
  expression
}

?>

 

 

<?php

$car = "Corvette";if ( $car == "Subaru" ) {
  echo "Subie Wave";
} elseif ( $car == "Jeep" ) {
  echo "Jeep Wave";
} elseif ( $car == "Corvette" ) {
  echo "Corvette Wave";
} else {
  echo "No Wave";
}

?>

 

  1. PHP assigns the value Corvette to the $car variable.
  2. PHP encounters the if statement. It tests to see if the value that’s stored inside of the $car variable is equal to Subaru. Since it’s not, it moves on to the elseif statement.
  3. It tests to see whether the value that’s stored inside of the $car variable is equal to Jeep. Since it’s not, it moves on to the next statement.
  4. PHP tests to see whether the value that’s stored inside of the $car variable is equal to Corvette. It is.
  5. PHP executes the code inside of that elseif statement. PHP outputs Corvette Wave.
  6. It skips over the else statement since it already found a match.

 

PHP Tutorial Series

Continue your learning with these articles

PHP Else Statement

What else is there?

PHP – P25: ELSE STATEMENT

Else statements execute when the if statement’s condition evaluates to false. Remember, the expressions inside of the if statement can only execute when the conditional expression evaluates to true.

PHP elseif statement

Elseif: Between if and Else

PHP – P26: elseif Statement

When you have more than 2 outcomes in your decision making, you’re going to need to use the PHP elseif statement. The elseif keyword goes in between the if and the else keywords.

PHP Ternary Operator

TIRED OF IF/ELSE? HOW ABOUT TERNARY?

PHP – P27: TERNARY OPERATOR

The ternary operator is a way to quickly express if/else statements. If the boolean expression evaluates to true, the “if_true” result is displayed, otherwise the “if_false” result is displayed.

Leave a Reply