PHP - Elseif
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"; }
PHP Code:
$employee = "Bob"; if($employee == "Ms. Tanner"){ echo "Hello Ma'am"; } elseif($employee == "Bob"){ echo "Good Morning Sir!"; }else { echo "Morning"; }
0 comments:
Post a Comment