Curriculum
This tutorial will teach you about the PHP if…else statement, which executes one code block when a condition is true and another code block when the condition is false.
When an expression is true, the if statement allows you to execute one or more statements:
<?php if ( expression ) { // code block }
If the expression is false, you may want to execute another code block. To accomplish this, add the else clause to the if statement:
<?php if ( expression ) { // code block } else { // another code block }
If the expression is true, PHP executes the code block following the if clause. If the expression returns false, PHP executes the code block following the else keyword.
The if…else statement is used in the following example to display a message based on the value of the $is authenticated variable:
<?php $is_authenticated = false; if ( $is_authenticated ) { echo 'Welcome!'; } else { echo 'You are not authorized to access this page.' }
In this case, the value of $is authenticated is false. As a result, the script executes the code block following the else clause. And you’ll get the following results:
You are not authorized to access this page.
The if…else statement, like the if statement, can be nicely mixed with HTML using the alternative syntax:
<?php if ( expression ): ?> <!--Show HTML code when expression is true --> <?php else: ?> <!--Show HTML code when expression is false --> <?php endif ?>
Because the endif keyword is the last statement in the PHP block, there is no need to follow it with a semicolon (;). The enclosing tag?> implies a semicolon by default.
The if…else statement is used in the following example to display the logout link if $is authenticated is true. If $is authenticated is set to false, the script displays the login link instead:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP if Statement Demo</title> </head> <body> <?php $is_authenticated = true; ?> <?php if ($is_authenticated) : ?> <a href="#">Logout</a> <?php else: ?> <a href="#">Login</a> <?php endif ?> </body> </html>