Tutorial 12: Else if


There's one last piece in the IF / ELSE puzzle. It's called else if (or elseif — pronounced "Else If"). ELSE IF is a kind of combination of IF and ELSE. PHP.net puts it nicely:

Like ELSE, it extends an IF statement to execute a different statement in case the original IF expression evaluates to FALSE. However, unlike ELSE, it will execute that alternative expression only if the else if conditional expression evaluates to TRUE.

If the above explanation is as clear as mud, the syntax looks like this:

if (expression) {
	
	// code to execute if the above expression is TRUE
	
} else if (different expression) {

	/* code to execute if first expression is FALSE
	   but the else if expression is TRUE */

} else {

	/* code to execute if neither
	   of the above expressions are TRUE */

}

Now, if we added some real PHP, it would look like this:

<?php
	
	$native_language = "Spanish";
	
	if ($native_language == "French") {
		
		echo "Bonjour! Vous parlez Français.";
		
	} else if ($native_language == "Spanish") {
		
		echo "¡Hola! Usted habla Español.";
		
	} else {
		
		echo "Hello! You probably speak English.";
		
	}

?>

Here's the commented code:

<?php
	
	// Setting the variable
	$native_language = "Spanish";
	
	// IF native language is French
	if ($native_language == "French") {
		
		// Echo some french!
		echo "Bonjour! Vous parlez Français.";
		
	// else if native language is Spanish	
	} else if ($native_language == "Spanish") {
		
		// Echo some spanish!
		echo "¡Hola! Usted habla Español.";
		
	// ELSE native language is neither of the above
	} else {
		
		// Echo some english!
		echo "Hello! You probably speak English.";
		
	}

?>
Check out the final example
©2019 Brad Hussey