Login | Contact Us | Site Map | Resources

PHP Conditions & Loops

Home > PHP Tutorial > Elseif

Elseif

If you like cheese you must be a mouse, else if you like lettuce you must be a rabbit, elseif you like chocolate you must be a human, else you must be a turtle. Yeah, that doesn't make much sense to me, either, but it's a fun way to get into the conditional programming mentality!

The elseif statement follows the if statement as a method of specifying (checking) alternative conditions to the if statement. Multiple elseif statements can be used.

<?php
  $color = "orange";
  if ($color=="purple") {
    echo "Purple conveys royalty, nobility & wisdom.";
  } elseif ($color=="orange") {
    echo "Orange conveys energy, warmth & flamboyancy.";
  } elseif ($color=="blue") {
    echo "Blue conveys peace, tranquility & security.";
  } else {
    echo "I dunno what that color conveys, sorry.";
  }
?>

After examining the example, can you determine which block of code will be executed when this program is run? If you guessed "the orange one" then we have a winner!

When a true condition is reached, php will skip the remaining elseif and else statements in that block, meaning that since the orange condition was true, the blue condition is never checked and the else statement is ignored. The else statement is not required at the end, but should be used if there is any possibility of the condition(s) not being met.

Your homework assignment is to write a shopping list (fictional, if necessary) in php and give it to a parent or sibling. Even if they cannot critique the php you should have fun seeing what they make of the instructions.