Lesson 4.7. Tests in PHP: if .. else

Syntax

Conditional statements in PHP are inspired by the C/C++ syntax:

<?php
if ($a > $b)
{
    echo "<p>a is greater than b</p>";
}
else
{
    echo "<p>a is not greater than b</p>";
}
?>

As in C programming, the use of curly brackets is only necessary when the instruction block contains several instructions.

In practice, when the test is used to display HTML, there is another syntax, more concise, which avoids the use of display functions like echo. The great advantage of this second solution is that HTML source code can be highlighted by the editor, which is not the case with the previous example:

<?php if ($a > $b): ?>
    <p>a is greater than b</p>
<?php else: ?>
    <p>a is not greater than b</p>
<?php endif; ?>
}

Short syntax

There is a short syntax which is appropriated when a single instruction is combined with a short test:

$var = (test) ? instruction if TRUE : instruction if FALSE;

This syntax is particularly convinient when combined with short tags:

<?= ($a>$b) ? '<p>a eis greater than b</p>'  : '<p>a is not greater than b</p>' ?>

The following example shows the three syntaxes:

Exercice

The following code displays two buttons (log in and log out):

Conditional statement for log in and log out buttons

<?php
$isLogged = true; // or false;
?>

<!-- Display if user is not logged -->
<div class="button_cont" align="center">
  <a 
    href='#'
    target="_blank" 
    style = "background: #0f0; text-decoration: none; padding: 10px; border-radius: 5px; display:inline-block;
    ">
  Log in
  </a>
</div>

<!-- Display if user is logged -->
<div class="button_cont" align="center">
  <a 
    href='#'
    target="_blank" 
    style = "background: #f00; color:white; text-decoration: none; padding: 10px; border-radius: 5px; display:inline-block;
    ">
  Log out
  </a>
</div>

Add a conditional statement in the script to display the appropriate button according to the current status of the boolean variable $isLogged:

See also


Last update : 09/17/2022