PHP Else Statement

What else is there?

The PHP 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.

The else keyword is appended right after the closing curly brace of the if statement.

 

<?php

$exercised = false;if ( $exercised ) {
  echo "You're being healthy.";
} else {
  echo "Crickets";

?>

 

When the programmer chooses to omit the curly braces from the if statement because of a single line expression, the else keyword is appended immediately below the expression that’s inside the if-statement body.

 

<?php

$best_tv_show_in_2020 = "Upload";if ( $best_tv_show_in_2020 == "Upload" )
  echo "It's Upload alright";
else
  echo "The best show is actually The Good Place";

?>

 

If you have a vendetta against curly braces, and you need to list multiple expressions inside of the else body, you can use the if:/else:/endif syntax.

 

<?php

$use_colons = false;if ( $use_colons ):
  echo "You are using colons";
  echo "Not good.";
else:
  echo "Still kinda using colons";
  echo "Still not good";
endif;

?>

 

 

PHP Tutorial Series

Continue your learning with these articles

Dino Cajic on PHP IF Statements

If You ONly Knew

PHP – P24: If Statement

The if statement is probably the first piece of code that you wrote. “If” statements are conditional statements, meaning that if the expression that they’re evaluating is true, the if statement will allow for the execution of the expressions inside of the if statement body.

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.

Leave a Reply