PHP Programing language

adplus-dvertising
PHP Else-if
Previous Home Next

If you want to check for only one condition then if/else statement is used for this program, it's very great. For example if you check your company $employee variable was the company owner is Hobert, and this company Vice President Ms. Tanner, or a regular employee? To check for these different conditions you would need the elseif statement.

Meaning of PHP Else-If

An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Red"). 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 the PHP evaluating your If...elseif...else statement it mean 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!"

Use of Elseif with IfElse

If we want to use elseif with the if else statement then Let's start out with the base case. and 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:

<?php
$employee = "Hobert";
if($employee == "Ms. Tanner")
	{
echo "hello Ms. Tanner";
    } 
else 
	{
echo "Good Morning, and How are you";
    }
?>

Again Now check, if we wanted to also check to see if the big boss Hobert was the employee we need to insert an elseif clause.

<?php
$employee = "Hobert";
if($employee == "Ms. Tanner")
	{
echo "hello Ms. Tanner";
    } 
elseif($employee == "Hobert")
	{
echo "Good Morning, and How are you";
    }
else 
	{
echo "I am Fine";
    }
?>

In this Program first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. And another Next, PHP checked the first elseif statement. $employee did in fact equal "Hobert" 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!

Previous Home Next