3 of 410 menu

The If Construct

The if construct checks the condition in parentheses and executes the code in curly braces if the condition is true. If the condition is false, the code inside the if block is not executed. The else and elseif operators can be used together with if to create complex conditions.

Syntax

if (condition) { // code to be executed if condition is true }

Example

Let's check if 5 is greater than 3:

<?php if (5 > 3) { echo '5 is greater than 3'; } ?>

Code execution result:

'5 is greater than 3'

Example

Using else for alternative execution:

<?php $num = 4; if ($num > 5) { echo 'Number is greater than 5'; } else { echo 'Number is 5 or less'; } ?>

Code execution result:

'Number is 5 or less'

Example

Using elseif for multiple conditions:

<?php $num = 5; if ($num > 5) { echo 'Number is greater than 5'; } elseif ($num == 5) { echo 'Number is exactly 5'; } else { echo 'Number is less than 5'; } ?>

Code execution result:

'Number is exactly 5'

See Also

  • the switch construct,
    which checks a value against multiple variants
byenru