5 of 410 menu

The elseif Construct

The elseif construct is used together with if to check additional conditions if the previous if or elseif condition was false. It allows creating chains of conditions and executing different code blocks depending on the check result.

Syntax

if (condition1) { // code if condition1 is true } elseif (condition2) { // code if condition2 is true } else { // code if all conditions are false }

Example

Let's check the value of a variable and output the corresponding message:

<?php $num = 10; if ($num > 15) { echo 'The number is greater than 15'; } elseif ($num > 5) { echo 'The number is greater than 5 but not greater than 15'; } else { echo 'The number is 5 or less'; } ?>

Code execution result:

'The number is greater than 5 but not greater than 15'

Example

Let's check the data type of a variable:

<?php $var = '123'; if (is_int($var)) { echo 'This is an integer'; } elseif (is_string($var)) { echo 'This is a string'; } else { echo 'This is another data type'; } ?>

Code execution result:

'This is a string'

See Also

  • the if construct,
    which checks a condition
  • the switch construct,
    which selects an execution option
byenru