Else

The if statement can be taken a step further with the else statement, used specifically as a follow-up to the if statement. What happens when an if statement is false? The else statement allows you to handle this possibility.

The else statement syntax is similar to the if statement syntax, but lacks a condition, and cannot be used alone. It must directly follow an if statement.

<?php
  $question = "What is the biggest ant in the world?";
  $answer = "An elephant!";
  if ($answer=="An elephant!") { echo "Yep, congrats."; }
  else { echo "Nope, sorry."; }
?>

In this example the condition is true (the answer is "An elephant!") so the else statement is ignored. If the condition was false, the else statement would be used:

<?php
  $age = 15;
  $discount_age = 60;
  if ($age>=$discount_age) {
    echo "Congratulations! You qualify for our senior discount.";
  } else {
    echo "Sorry, but you do not qualify for our senior discount.";
  }
?>

Now we see a condition stating that if the age is greater than or equal to the discount age, you would qualify for a senior discount, otherwise (else) you will not qualify. Unless you significantly raise the value of the age variable, there will be no senior discounts for you!

Next up we will learn how to add additional conditions into an if...else statement using elseif.