ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

22 – PHP elseif Statement

To check for one condition, if/else statement is a powerful tool to use. However, if you check the variable $emp_name for the name of the employee which is Craig the President, Kenjie the CEO or a Manager of the company, will need an elseif statement to check 3 or more conditions.

 

What is elseif in php?

An elseif statement is used for three or more conditions. This elseif statement must come after the if statement because you cannot use it without having an if statement.

 

If…elseif…else statement once evaluated in PHP it see first if the statement is equal or  true. But, if the test results into false, it will immediately check first the elseif statement. Once proven false, the next elseif statement will be checked or it will evaluate the else segment if there are no more elseif statements, if it exists.

 

Using elseif with if…else

Picture out the simple problem described above, we want to find out if the employee is the President Mr. Craig. An if else statement is what we need for this example.

 

if Code:

$emp_name= "Craig";
if($emp_name== "Kenjie"){
	echo "Hello Sir";
} else {
	echo "Morning Sir";
}

However, if we also want to check if President Craig was the employee well, we have to insert an elseif clause.

elseif Code:

$emp_name= "Craig";
if($emp_name== "kenjie"){
	echo "Hello Sir";
} elseif($emp_name== "Craig"){
	echo "Good Morning Sir!";
}else {
	echo "Morning Sir";
}

Result:

Good Morning Sir!

PHP checked if $emp_name was equal to “Craig“, which is evaluated to false. Then, the first elseif statement is checked. The $emp_name was indeed equal to “Craig so, it printed out the phrase “Good Morning Sir!” We could also insert more elseif statement if we wanted to check out for more of the employee names.

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!