PHP Elseif (PHP Tutorial part 13)

১২/০৬/২০১১ ০২:৪০:০০ AM | , | 0 comments »

An if/else statement is great if you only need to check for one condition. However, what would you do if you wanted to check if your $employee variable was the company owner Bob, the Vice President Ms. Tanner, or a regular employee? To check for these different conditions you would need the elseif statement.

PHP - Elseif What is it?

An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Ted"). Just like an if statement, an elseif statement also contains a conditional statement, but it must be preceded by an if statement. You cannot have an elseif statement without first having an if statement.
When PHP evaluates your If...elseif...else statement it will first see if the If statement is true. If that tests comes out false it will then check the first elseif statement. If that is false it will either check the next elseif statement, or if there are no more elseif statements, it will evaluate the else segment, if one exists (I don't think I've ever used the word "if" so much in my entire life!). Let's take a look at a real world example.

PHP - Using Elseif with If...Else

Let's start out with the base case. Imagine we have a simpler version of the problem described above. We simply want to find out if the employee is the Vice President Ms. Tanner. We only need an if else statement for this part of the example.

PHP Code:

$employee = "Bob";
if($employee == "Ms. Tanner"){
 echo "Hello Ma'am";
} else {
 echo "Morning";
}
Now, if we wanted to also check to see if the big boss Bob was the employee we need to insert an elseif clause.

PHP Code:

$employee = "Bob";
if($employee == "Ms. Tanner"){
 echo "Hello Ma'am";
} elseif($employee == "Bob"){
 echo "Good Morning Sir!";
}else {
 echo "Morning";
}

Display:

Good Morning Sir!
PHP first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. Next, PHP checked the first elseif statement. $employee did in fact equal "Bob" so the phrase "Good Morning Sir!" was printed out. If we wanted to check for more employee names we could insert more elseif statements!
Remember that an elseif statement cannot be used unless it is preceded by an if statement!