Please enable JavaScript to view this site.

Process Designer

Navigation: PHP API > Introduction to PHP

If , Else and Switch statement

Scroll Prev Top Next More

Often you may want to execute different program code depending on met conditions. To check if conditions are met, if and switch statements can be used. Example:

<?php

// storing the variable $user with the text admin

$user = "admin";

/*

Check, if the variable $user contains admin

To check == must be used

*/ 

If ($user == "admin")

{

         // If $user == "admin", display Hello Administrator

         echo "Hello Administrator!";

} else {

         // Otherwise display Hello Guest

         echo "Hello Guest!";

}

?>

Since admin was saved in the variable $user "Hello Administrator" will be displayed. To check if the statement is functional, you can assign a different text to the variable and reload the page. "Hello Guest" should now be displayed.

To distinguish between two conditions you can either use an else-if statement or solve it more elegantly using a switch statement. Example:

<?php

// storing the variable $user with the text admin

$user = "admin";

 

/*

Distinguishing between different cases by if/else/elseif

*/ 

if ($user == "admin") {

 echo "Hello Administrator!";

} elseif ($user == "manager") {

 echo "Hello Manager!";

} elseif ($user == "user") {

 echo "Hello User!";

} else {

 echo "Hello Guest!";

}        

 

/*

Distinguishing between different cases with switch

*/ 

switch ($user) {

 case "admin":

         echo "Hello Administrator!";

         break;

 case "manager":

         echo "Hello Manager!";

         break;

 case "user":

         echo "Hello User!";

         break;

 default:

         echo "Hello Guest!";

}

?>

elseif is a combined expression of else and if and simply saves writing time. Each case has to start with a case and end with a break except for the last case. The last one does not need a break. This is optional.