25 Aug 09 PHP Programming Tutorial: Else and ElseIf Statements



In the previous article, we discussed PHP If Statements and showed some quick examples. Now we’ll go deeper into this subject and explore the Else and Elseif statements.

Let’s go ahead and jump into some code:

<?php
$fruit1 = apple; // Our first variable
$fruit2 = orange; // Our second variable
 
// if fruit1 is an apple, proceed.
if ($fruit1 == "apple") {
echo "We have an apple.";
}
?>

So in this code, we created two variables to contain our names of fruit. We then created an If Statement and we echo a string if the condition is met. In this case, the condition is true, so it echos “We have an apple.” Let’s add some more:

<?php
$fruit1 = apple; // Our first variable
$fruit2 = orange; // Our second variable
 
if ($fruit1 == "grapes") { // $fruit1 is not grapes, so this is false.
echo "We have some grapes."; // PHP will ignore this.
} else {
echo "We do not have any grapes.";
}
?>

In this code we added the Else statement. This tells PHP what to do in case the If Statement is false. If you don’t provide an Else or Elseif statement, then PHP will just do nothing if the If Statement fails. And that’s fine because sometimes you don’t want PHP to do anything.

The Elseif statement is similar to an If Statement. Basically, if the first If Statement fails, then the Elseif statement gets a turn. If PHP determines the Elseif statement is true, then it will run the statement inside. Let’s try using an Elseif Statement. Be sure to read the comments to follow along:

<?php
$fruit1 = apple; // Our first variable
$fruit2 = orange; // Our second variable
 
if ($fruit1 == "grapes") { // $fruit1 is not grapes, so this is false.
echo "We have some grapes."; // PHP will ignore this.
} elseif ($fruit2 == "orange") { // This is true, so PHP proceeds!
echo "At least we have oranges!"; // Yummy.
} else { // PHP ignores this, because it already proceeded with the Elseif statement.
echo "We do not have any grapes or oranges.";
}
?>

And there we have it. This is the normal way of spacing out If, Elseif, and Else statements. But remember, the spacing with PHP isn’t important. The code below does the exact same thing:

<?php
$fruit1 = apple; // Our first variable
$fruit2 = orange; // Our second variable
 
if ($fruit1 == "grapes") // $fruit1 is not grapes, so this is false.
{
echo "We have some grapes."; // PHP will ignore this.
}
elseif ($fruit2 == "orange") // This is true, so PHP proceeds!
{
echo "At least we have oranges!"; // Yummy.
}
else // PHP ignores this, because it already proceeded with the Elseif statement.
{
echo "We do not have any grapes or oranges.";
}
?>

Ultimately the way you style your code is up to your preference.

Go back to Building PHP Scripts.

Tags: , , , ,

Leave a Comment