Else If [#18] Code Dynamic Websites with PHP

Опубликовано: 14 Декабрь 2024
на канале: Brad Hussey
3,388
34

Lecture 18: Else if

There's one last piece in the IF / ELSE puzzle. It's called ELSEIF (pronounced "Else If"). ELSEIF 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 ELSEIF 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

} elseif (different expression) {

/* code to execute if first expression is FALSE

but the ELSEIF 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:


$native_language = "Spanish";

if ($native_language == "French") {

echo "Bonjour! Vouz parlez Français.";

} elseif ($native_language == "Spanish") {

echo "¡Hola! Usted habla Español.";

} else {

echo "Hello! You probably speak English.";

}


Here's the commented code:


// Setting the variable

$native_language = "Spanish";

// IF native language is French

if ($native_language == "French") {

// Echo some french!

echo "Bonjour! Vouz parlez Français.";

// ELSEIF native language is Spanish

} elseif ($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.";

}

DOWNLOAD COURSE FILES HERE
http://www.bradhussey.ca/download-php...