The elseif Statement

The elseif statement allows you to test for several conditions simultaneously.Each elseif has its own code of block that comes directly after the elseif condition. The elseif must come after the if statement and before an else statement.

if (conditional expression) {
  code to be executed if condition is true;
}
elseif {
  code to be executed if condition is true;
}
elseif {
  code to be executed if condition is true;
}
else {
  code to be executed if condition is false;
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
// compare a string
$wheather = "sunny";
if ($wheather == "bad") {
   echo "Well today is not a $wheather day.<br />";
} elseif ($wheather == "sunny") {
   echo "Well I like a $wheather day.<br />";
} else {
   echo "The day is OK.<br />";
}

// use logical operators
$temperature = 60;
if ($temperature > 100) {
   echo "It's too hot.<br />";
} elseif ($temperature > 80) {
   echo "It's hot.<br />";
} elseif ($temperature > 60) {
   echo "It's warm.<br />";
} else {
   echo "It's cold.<br />";
}
?>
</p>
</body>
</html>

View the effect

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>The elseif Statement</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<h2>Auto Parts</h2>
<b>Your order is as follows:</b>
<p>
<?php
$tireqty = 15;
$oilqty = 3;
$sparkqty = 3;
$totalqty = $tireqty + $oilqty + $sparkqty;
// give a discount for tires
if ($tireqty<10)
	$discount = 0;
elseif ($tireqty>=10 && $tireqty<50)
	$discount = 5;
elseif ($tireqty>=50)
	$discount = 10;

if ($totalqty == 0)
{
	echo "You did not order anything.<br />";
}
else
{
  if ($tireqty>0)
	echo "$tireqty tires. You got $discount% discount.<br />";
  if ($oilqty>0)
	echo "$oilqty bottles of oil<br />";
  if ($sparkqty>0)
	echo "$sparkqty spark plugs<br />";
}

?>
</p>
</body>
</html>

View the effect


Conditional Tests | The if Statement | The else Statement | The elseif Statement | The switch Statement
© 2008: Hann So
email: hso@voyager.deanza.edu