PHP Tutorial > PHP Commands > ELSEIF

In IF ELSE, PHP provides a way to do an either/or selection. What if you need more than two options? This is where ELSEIF comes in. ELSEIF is built on top of the IF ELSE construct to provide additional options. The basic syntax is as follows:

IF (conditional statement 1) {
  [code if condition statement 1 is true]
ELSEIF (conditional statement 2) {
  [code if condition statement 2 is true]
  [code if none of the above is true]

ELSEIF can be repeated as many times as needed prior to the ELSE statement.

Let's use an example. Assuming we have the following piece of code:

$sample = 10;
IF ($sample > 15) {
  print "Level 1";
ELSEIF ($sample > 5) {
  print "Level 2";
  print "Level 3";

The output of the above code is:

Level 2

This is because the first condition is false, and the second condition is true. Therefore, the code in the bracket after ELSEIF is executed.


Copyright © 2022  All Rights Reserved.  Privacy Policy   About   Contact