PHP if else

Summary: in this tutorial, you’ll learn about the PHP if...else statement that executes a code block when a condition is true or another code block when the condition is false.

Introduction to PHP if-else statement

The if statement allows you to execute one or more statements when an expression is true:

<?php
if ( expression ) {
    //  code block
}Code language: HTML, XML (xml)

Sometimes, you want to execute another code block if the expression is false. To do that, you add the else clause to the if statement:

<?php
if ( expression ) {
    // code block
} else {
    // another code block
}Code language: HTML, XML (xml)

In this syntax, if the expression is true, PHP executes the code block that follows the if clause. If the expression is false, PHP executes the code block that follows the else keyword.

The following flowchart illustrates how the PHP if-else statement works:

The following example uses the if...else statement to show 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.'
}Code language: HTML, XML (xml)

In this example, the $is_authenticated is false. Therefore, the script executes the code block that follows the else clause. And you’ll see the following output:

You are not authorized to access this page.Code language: JavaScript (javascript)

PHP if…else statement in HTML

Like the if statement, you can mix the if...else statement with HTML nicely 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 ?>Code language: HTML, XML (xml)

Note that you don’t need to place a semicolon (;) after the endif keyword because the endif is the last statement in the PHP block. The enclosing tag ?> automatically implies a semicolon.

The following example uses the if...else statement to show the logout link if $is_authenticated is true. If the $is_authenticated is false, the script shows 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>Code language: HTML, XML (xml)

Summary

  • Use the PHP if...else statement to execute a code block when a condition is true.
Did you find this tutorial useful?