4 of 410 menu

The Else Construct

The else construct is part of the conditional if construct and is executed when the main condition is false. It should always follow after an if or elseif block.

Syntax

if (condition) { // code if true } else { // code if false }

Example

Check if 5 is greater than 3:

<?php if (5 > 3) { echo 'True'; } else { echo 'False'; } ?>

Code execution result:

'True'

Example

Check if 2 is less than 1:

<?php if (2 < 1) { echo 'True'; } else { echo 'False'; } ?>

Code execution result:

'False'

Example

Usage with elseif:

<?php $num = 0; if ($num > 0) { echo 'Positive'; } elseif ($num < 0) { echo 'Negative'; } else { echo 'Zero'; } ?>

Code execution result:

'Zero'

See Also

  • the if construct,
    which checks a condition
  • the elseif construct,
    which checks an alternative condition
byenru