Home

If/Else Conditional Statements

If a Condition is True

A Re-Introduction

As seen in Lesson 7, the most fundamental conditional statement uses the if keyword. It takes a Boolean expression in its parentheses. Here are examples:

employment1.php

<!DOCTYPE html>
<html>

<head>
<title>Employment Application</title>
<style type="text/css">
#Container
{
    margin: auto;
    width:  400px;
}
#MainTitle
{
    font-size:   16pt;
    font-weight: bold;
    text-align:  center;
}
.centered { text-align: center }
</style>
</head>

<body>

<div id="Container">
<p id="MainTitle">Employment Application</p>

<form name="frmEmploymentApplication"
      action="employment2.php" method="post">
<table>
  <tr>
    <td>Employee #:</td>
    <td><input name="txtEmployeeNumber" type="text" /> *</td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><input name="txtFirstName" type="text" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><input name="txtLastName" type="text" /> *</td>
  </tr>
  <tr>
    <td colspan="2" class="centered">
      <input name="btnSubmit" type="submit"
             value="Submit Application" /></td>
  </tr>
</table>
  
</form>
</div>
</body>
</html>

employment2.php

<!DOCTYPE html>
<html>

<head>
<title>Employment Application</title>
<style type="text/css">
#Container
{
    margin: auto;
    width:  400px;
}
#MainTitle
{
	font-size:   16pt;
	font-weight: bold;
	text-align:  center;
}
.centered { text-align: center }
</style>
</head>

<body>

<div id="Container">
<p id="MainTitle">Employment Application</p>

<?php
$employeeNumber = htmlspecialchars($_POST['txtEmployeeNumber']);
$firstName      = htmlspecialchars($_POST['txtFirstName']);
$lastName       = htmlspecialchars($_POST['txtLastName']);
?>

<table>
  <tr>
    <td>Employee #:</td>
    <td>

<?php
    if($employeeNumber != "")
        echo $employeeNumber;
?>

    </td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td>

<?php
    if($employeeNumber != "")
        echo $firstName;
?>

    </td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td>

<?php
    if($employeeNumber != "")
        echo $lastName;
?>

    </td>
  </tr>
</table>
  
</form>
</div>

</body>

</html>

Here is an example of using the webpages:

If a Condition is True

If a Condition is True

If a Condition is True

If a Condition is True

If a Condition is True

The Body of a Conditional Statement

The section where you define what to do about a conditional statement is referred to as its body. You can delimite that section with curly brackets. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Gas Utility Company</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  250pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
</style>
</head>
<body>

<?php
echo "<form name='frmCalculation' method='post'>
      <div id='formulation'>
      <p id='main-title'>Gas Utility Company</p>";

      $pricePerCCF    = 50.00;
      $consumption    = htmlspecialchars($_POST['txtConsumption']);
      
      if($consumption >= 0.50){
          $pricePerCCF = 35.00;
      }

      $monthlyCharges = $consumption * $pricePerCCF;

echo "      <table border='4'>
        <tr>
          <td>Consumption:</td>
          <td>
	    <input name='txtConsumption' type='text' style='width: 80px' value='";

echo $consumption;

echo "' /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td>
	    <input name='Submit' type='submit' value='Calculate' />
          </td>
        </tr>
        <tr>
          <td>Price per CCF:</td>
          <td><input name='txtPricePerCCF' type='text' value='";

echo $pricePerCCF;

echo"' /></td>
        </tr>
        <tr>
          <td>Monthly Charges:</td>
          <td><input name='txtMonthlyCharges' type='text' value='";

echo $monthlyCharges;

echo "' /></td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of using the webpage:

If a Condition is True

If a Condition is True

You can include any HTML code anywhere in the loop as long as you delimit the loop code with its own PHP delimitiers. Here is an example:

<?php if($consumption >= 0.50){  ?>
          $pricePerCCF = 35.00;

<p>Something here!</p>

<?php } ?>

Delimiting the body of the conditional statement is especially useful and required if the statement is made of various lines. The opening curly bracket can be written on the next line from the condition. Here is an example:

<?php
echo "<form name='frmPayroll' method='post'>
      <p><b>Employee Payroll</b></p>";

      $hourlySalary = (float)htmlspecialchars($_POST['txtHourlySalary']);
      $overtimeSalary = $hourlySalary * 1.50;

      $weeklyTime   = (float)htmlspecialchars($_POST['txtWeeklyTime']);
      //$weeklySalary = $hourlySalary * $weeklyTime;

      $regularTime = $weeklyTime;
      $regularPay  = $hourlySalary * $regularTime;
      $overtime    = 0.00;
      $overtimePay = 0.00;

      if($weeklyTime >= 40.00)
      {
          $regularTime = 40.00;
          $regularPay  = $hourlySalary * 40.00;
          $overtime    = $weeklyTime - 40.00;
          $overtimePay = $overtime * $overtimeSalary;
      }

      $netPay = $regularPay + $overtimePay;

echo "      <table border='4'>
        <tr>
          <td>Hourly Salary:</td>
          <td>
	    <input name='txtHourlySalary' type='text' 
	           style='width: 60px' value='$hourlySalary' /></td>
        </tr>
        <tr>
          <td>Weekly Time:</td>
          <td>
	    <input name='txtWeeklyTime' type='text' 
	           style='width: 60px' value='$weeklyTime' />
	    <input name='Submit' type='submit' value='Calculate' />
          </td>
        </tr>
        <tr>
          <td>Regular Time:</td>
          <td>
	    <input name='txtRegularTime' type='text' value='$regularTime' /></td>
        </tr>
        <tr>
          <td>Regular Pay:</td>
          <td>
	    <input name='txtRegularPay' type='text' value='$regularPay' /></td>
        </tr>
        <tr>
          <td>Regular Time:</td>
          <td>
	    <input name='txtOvertime' type='text' value='$overtime' /></td>
        </tr>
        <tr>
          <td>Regular Pay:</td>
          <td>
	    <input name='txtOvertimePay' type='text' value='$overtimePay' /></td>
        </tr>
        <tr>
          <td>Net Pay:</td>
          <td><input name='txtNetPay' type='text' value='$netPay' /></td>
        </tr>
      </table>
    </div>
    </form>";
?>

Here is an example of using the webpage:

The Body of a Conditional Statement

The Body of a Conditional Statement

The Body of a Conditional Statement

The Body of a Conditional Statement

The opening curly bracket can also be written on the same line as the condition. Here is an example:

if($weeklyTime >= 40.00) {
    $regularTime = 40.00;
    $regularPay  = $hourlySalary * 40.00;
    $overtime    = $weeklyTime - 40.00;
    $overtimePay = $overtime * $overtimeSalary;
}

The body of the conditional statement can contain its own HTML code. In this case, you can include the HTML code in echo. Here is an example:

employment1.php

<!DOCTYPE html>
<html>

<head>
<title>Employment Application</title>
<style type="text/css">
#Container
{
    margin: auto;
    width:  250px;
}
#MainTitle
{
    font-size:   16pt;
    font-weight: bold;
    text-align:  center;
}
.centered { text-align: center }
</style>
</head>

<body>

<div id="Container">
<p id="MainTitle">Employment Application</p>

<form name="frmEmploymentApplication"
      action="employment3.php" method="post">
<table style="width: 100%">
  <tr>
    <td>Employee #:</td>
    <td><input name="txtEmployeeNumber" type="text" /> *</td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><input name="txtFirstName" type="text" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><input name="txtLastName" type="text" /> *</td>
  </tr>
  <tr>
    <td colspan="2" class="centered">
      <input name="btnSubmit" type="submit"
             value="Submit Application" /></td>
  </tr>
</table>
  
</form>
</div>

</body>

</html>

employment3.php

<!DOCTYPE html>
<html>

<head>
<title>Employment Application</title>
<style type="text/css">
#Container
{
    margin: auto;
    width:  250px;
}
#MainTitle
{
	font-size:   16pt;
	font-weight: bold;
	text-align:  center;
}
.centered { text-align: center }
</style>
</head>

<body>

<div id="Container">
<p id="MainTitle">Employment Application</p>

<?php
$employeeNumber = htmlspecialchars($_POST['txtEmployeeNumber']);
$firstName      = htmlspecialchars($_POST['txtFirstName']);
$lastName       = htmlspecialchars($_POST['txtLastName']);
?>

<?php
    if($employeeNumber != ""){
        echo "<table>
                <tr>
                  <td>Employee #:</td>
                  <td>$employeeNumber</td>
                </tr>
                <tr>
                  <td>First Name:</td>
                  <td>$firstName</td>
                </tr>
                <tr>
                  <td>Last Name:</td>
                  <td>$lastName</td>
                </tr>
              </table>";
}
?>
</div>
</body>
</html>

Here is an example of using the webpages:

If a Condition is True

If a Condition is True

If a Condition is True

If a Condition is True

If a Condition is True

The body can also contain independent or dependent PHP code. Make sure each PHP section starts and closes with the appropriate delimiters. Here is an example:

employment1.php

. . .

<p id="MainTitle">Employment Application</p>

<form name="frmEmploymentApplication"
      action="employment4.php" method="post">
<table style="width: 100%">

. . .

employment4.php

<!DOCTYPE html>
<html>

<head>
<title>Employment Application</title>
<style type="text/css">
#Container
{
    margin: auto;
    width:  250px;
}
#MainTitle
{
	font-size:   16pt;
	font-weight: bold;
	text-align:  center;
}
.centered { text-align: center }
</style>
</head>

<body>

<div id="Container">
<p id="MainTitle">Employment Application</p>

<?php
$employeeNumber = htmlspecialchars($_POST['txtEmployeeNumber']);
$firstName      = htmlspecialchars($_POST['txtFirstName']);
$lastName       = htmlspecialchars($_POST['txtLastName']);
?>

<?php if($employeeNumber != ""){ ?>

<?php
    echo "<table>
            <tr>
              <td>Employee #:</td>
              <td>$employeeNumber</td>
            </tr>
            <tr>
              <td>First Name:</td>
              <td>$firstName</td>
            </tr>
            <tr>
              <td>Last Name:</td>
              <td>$lastName</td>
            </tr>
          </table>";
?>

<?php } ?>
</div>
</body>
</html>

Besides the curly brackets, PHP supports another technique to delimit a conditional statement. To apply it:

Here is an example:

if($weeklyTime >= 40.00):
    $regularTime = 40.00;
    $regularPay  = $hourlySalary * 40.00;
    $overtime    = $weeklyTime - 40.00;
    $overtimePay = $overtime * $overtimeSalary;
endif

If there is another statement after this section, remember to add a semicolon. If the conditional statement is made of different PHP parts, still replace the opening curley bracket with a colon and the closing curly bracket with endif. Here is an example:

<?php
    if($employeeNumber != ""): ?>

<?php
    echo "<table>
            <tr>
              <td>Employee #:</td>
              <td>$employeeNumber</td>
            </tr>
            <tr>
              <td>First Name:</td>
              <td>$firstName</td>
            </tr>
            <tr>
              <td>Last Name:</td>
              <td>$lastName</td>
            </tr>
          </table>"; ?>

<?php endif ?>

What Else if a Condition is False

Introduction

When used by itself, the if condition does not specify what to do if its comparison produces a false result. To let you consider what to do if the condition is false, PHP provides the else keyword. The formula to use it is:

if(variable-or-value1 operator variable-or-value2)
    statement1;
else
    statement2

This time, the if statement is processed by statement1. If the condition is false, add the else. The statement2 would be processed if the comparison of the operator produces a false resust. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Employee Payroll</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  250pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
.short-text { width: 60px }
</style>
</head>
<body>

<?php
echo "<form name='frmIceCream' method='post'>
      <div id='formulation'>
      <p id='main-title'>Ice Cream Order</p>";

      $base_price = 0.00;
      $scoops = htmlspecialchars($_POST['txtScoops']);
      
      if($scoops == 1)
          $base_price = 1.95;
      else
          $base_price = 1.25;

      $orderTotal = $base_price * $scoops;

echo "      <table border='4'>
        <tr>
          <td>How many scoops:</td>
          <td><input name='txtScoops' type='text' 
                     class='short-text' value='$scoops'></input>
              <input name='Submit' type='submit' value='Get Base Price'></input></td>
        </tr>
        <tr>
          <td>Base Price/Scoop:</td>
          <td><input name='txtBasePrice' type='text' 
                     class='short-text' value='$base_price'></input></td>
        </tr>
        <tr>
          <td>Order Total:</td>
          <td>$orderTotal</td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of using the webpage:

If Something Else is True

If Something Else is True

If Something Else is True

What Else If Another Condition is Possible

The if and else conditions we have used so far provide only two options. Sometimes, more alternatives must be considered. This is done using the elseif keyword. If you have two combinations of comparisons to perform, the formula to follow is:

if(variable-or-value1 operator1 variable-or-value2)
    statement1
elseif(variable-or-value3 Operator2 variable-or-value4)
    statement2

If you have many combinations of comparisons to perform, you can use an elseif comparison for each condition. The formula to follow is:

if(variable-or-value1 Operator1 variable-or-value2)
    Statement1
elseif( variable-or-value1 Operator1 variable-or-value2)
    statement2
elseif( variable-or-value3 Operator2 variable-or-value4)
    statement3
elseif( variable-or-value5 Operator3 variable-or-value6)
    statement4

Here is an example:

payroll1a.php

<?php
echo "<html>
      <head><title>Payroll Preparation</title>
      </head>
      <style type='text/css'>
      #title {
          font-size:   28px;
          font-weight: bold;
          text-align:  center;
      }
      #whole {
          margin: auto;
          width:  500px;
      }
      #btnSubmit {
          width:  400px;
          height: 32px;
      }
      #btnContainer, .centered { text-align: center }
      .sizer { width: 64px }
      </style>
      </head>
      <body>
      <div id='whole'>
       <form name='frmPayroll' action='payroll1b.php' method='POST'>
       <p id='title'>Payroll Preparation</p>
 
       <table align='center'>
         <tr>
           <td><b>Employee/Time Information</b>
             <table>
               <tr>
                 <td>Employee Name:</td>
                 <td><input type='text' name='txtEmployeeName'></input></td>
               </tr>
               <tr>
                 <td>Hourly Salary:</td>
                 <td><input type='text' name='txtHourlySalary' 
                            class='sizer' value='0.00'></input></td>
               </tr>
               <tr>
                 <td>Time Worked:</td>
                 <td><input type='text' name='txtTimeWorked' 
                            class='sizer' value='0.00'></input></td>
               </tr>
               <tr>
                 <td>&nbsp;</td>
                 <td>&nbsp;</td>
               </tr>
             </table>
           </td>
           <td><b>Payroll Period</b>
             <table>
               <tr>
                 <td>Weekly</td>
                 <td><input type='radio' name='rdoPayrollPeriod' 
                            value='Weekly'></input></td>
               </tr>
               <tr>
                 <td>Biweekly</td>
                 <td><input type='radio' name='rdoPayrollPeriod' 
                            value='Biweekly'></input></td>
               </tr>
               <tr>
                 <td>Semimonthly</td>
                 <td><input type='radio' name='rdoPayrollPeriod' 
                            value='Semimonthly'></input></td>
               </tr>
               <tr>
                 <td>Monthly</td>
                 <td><input type='radio' name='rdoPayrollPeriod' 
                           value='Monthly'></input></td>
               </tr>
             </table>
           </td>
         </tr>
         <tr>
           <td colspan='2' id='btnContainer'>
             <input type='submit' value='Create Payroll' id='btnSubmit' /></td>
         </tr>
       </table>
       </form>
       </div>
      </body>
      </html>";
?>

payroll1b.php

<?php
echo "<html>
     <head><title>Payroll Preparation</title>
     </head>
     <style type='text/css'>
     #title {
         font-size:   28px;
         font-weight: bold;
         text-align:  center;
     }
     #whole {
         margin: auto;
         width:  500px;
     }
     #btnSubmit {
         width:  400px;
         height: 32px;
     }
     #btnContainer, .centered { text-align: center }
     .sizer { width: 64px }
     </style>
     </head>
     <body>
     <div id='whole'>
      <form name='frmPayroll' method='POST'>
      <p id='title'>Payroll Preparation</p>";

      $incomeTax = 0.00;

      $employeeName  = htmlspecialchars($_POST['txtEmployeeName']);
      $hourlySalary  = (float)htmlspecialchars($_POST['txtHourlySalary']);
      $timeWorked    = (float)htmlspecialchars($_POST['txtTimeWorked']);
      $payrollPeriod = htmlspecialchars($_POST['rdoPayrollPeriod']);

      $rawSalary     =  $hourlySalary * $timeWorked;

      if(htmlspecialchars($_POST['rdoPayrollPeriod']) == 'Weekly')
          $incomeTax = 99.10 + ($rawSalary * 0.25);
      elseif(htmlspecialchars($_POST['rdoPayrollPeriod']) == 'Biweekly')
          $incomeTax = 35.50 + ($rawSalary * 0.15);
      elseif(htmlspecialchars($_POST['rdoPayrollPeriod']) == 'Semimonthly')
          $incomeTax = 38.40 + ($rawSalary * 0.15);
      elseif(htmlspecialchars($_POST['rdoPayrollPeriod']) == 'Monthly')
          $incomeTax = 76.80 + ($rawSalary * 0.15);

      $netPay = $rawSalary - $incomeTax;

echo "      <table align='center'>
        <tr>
          <td>Employee Name:</td>
          <td>$employeeName</td>
        </tr>
        <tr>
          <td>Hourly Salary:</td>
          <td>$hourlySalary</td>
        </tr>
        <tr>
          <td>Time Worked:</td>
          <td>$timeWorked</td>
        </tr>
        <tr>
          <td>Raw Salary:</td>
          <td>$rawSalary</td>
        </tr>
        <tr>
          <td>Payroll Period:</td>
          <td>$payrollPeriod</b>
        </tr>
        <tr>
          <td>Income Tax:</td>
          <td>$incomeTax</td>
        </tr>
        <tr>
          <td>Net Pay:</td>
          <td>$netPay</td>
        </tr>
      </table>
      </form>
      </div>
      </body>
      </html>";
?>

Here is an example of using the webpages:

If Something Else is True

If Something Else is True

If Something Else is True

If none of the elseif comparisons applies, you can add a last else statement. The formula to follow is:

if(variable-or-value1 operator1 variable-or-value2)
    statement1;
elseif(variable-or-value1 operator_n1 variable-or-value2)
    statement2;
elseif(variable-or-value3 operator2 variable-or-value4)
    statement3;
elseif(variable-or-value5 operator3 variable-or-value6)
    statement3;
else
    statement_X

Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Employee Payroll</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  250pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
.short-text { width: 60px }
</style>
</head>
<body>

<?php
echo "<form name='frmIceCream' method='post'>
      <div id='formulation'>
      <p id='main-title'>Ice Cream Order</p>";

      $base_price = 0.00;
      $scoops  = htmlspecialchars($_POST['txtScoops']);
      
      if($scoops == 1)
          $base_price = 1.95;
      elseif($scoops == 2)
          $base_price = 1.50;
      else
          $base_price = 1.25;

echo "      <table border='4'>
        <tr>
          <td>How many scoops:
          <td><input name='txtScoops' type='text' 
                     class='short-text' value='$scoops'></input></td>
          <td><input name='Submit' type='submit' value='Get Base Price'></input></td>
        </tr>
        <tr>
          <td>Base Price/Scoop:</td>
          <td><input name='txtBasePrice' type='text' 
                     class='short-text' value='$base_price'></input></td>
          <td>&nbsp;</td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of using the webpage:

If Something Else is True

If Something Else is True

If Something Else is True

The Body of an If/Else Conditional Statement

If the conditional statement is made of different if, elseif, and/or else sections, each conditional line must end with a colon and the whole statement must end with the endif keyword.

Boolean Variables

A Boolean variable is one that holds a true or a false value. As seen in our introduction, when initialyzing the variable, you can assign it true or false. As an alternative, you can assign a comparison operation to it. The result of the operation can be stored in a variable. The formula to follow would be:

$variable-name = operand1 operator operand2

Here is an example:

<?php
echo "<div style='width: 300pt; margin: auto;'>";

$score = htmlspecialchars($_POST['txtScore']);
?>
<form name="frmGrade" method="post">
<p>Enter Customer Credit Score: 
   <input type="text" name="txtScore" style="width: 60px" value="

<?php echo $score ?>

" /></p>
<p style="text-align: center">
   <input type="submit" name="btnSubmit" value="Make Decision" /></p>
</form>

<?php
$goodCredit = $score >= 680;

if($goodCredit == true)
    echo "Decision: The loan is approved";
else
    echo "Decision: The loan is denied";
echo "</div>";
?>

Here is an example of using the webpage:

Boolean Variables

Boolean Variables

To make your code easy to read, you can (should) include the Boolean operation in parentheses. The formula to follow would be:

$variable-name = (operand1 operator operand2)

Here is an example:

<?php $goodCredit = ($score >= 680) ?>

To delimit the conditiion, every line that has a condition must end with a colon. The end of the whole conditional statement must end with the endif keyword. Here is an example:

<?php
echo "<div style='width: 300pt; margin: auto;'>";

$score = htmlspecialchars($_POST['txtScore']);
?>
<form name="frmGrade" method="post">
<p>Enter Customer Credit Score: 
   <input type="text" name="txtScore" style="width: 60px" value="

<?php echo $score ?>

" /></p>
<p style="text-align: center">
   <input type="submit" name="btnSubmit" value="Make Decision" /></p>
</form>

<?php $goodCredit = $score >= 680 ?>

<?php
if($goodCredit == true):
    echo "Decision: The loan is approved";
else:
    echo "Decision: The loan is denied";
endif
?>

<?php echo "</div>" ?>

If there is any PHP code after the conditional statement, the keyword must end with a semicolon. Here is an example:

<?php
echo "<div style='width: 300pt; margin: auto;'>";

$score = htmlspecialchars($_POST['txtScore']);
?>
<form name="frmGrade" method="post">
<p>Enter Customer Credit Score: 
   <input type="text" name="txtScore" style="width: 60px" value="

<?php echo $score ?>

" /></p>
<p style="text-align: center">
   <input type="submit" name="btnSubmit" value="Make Decision" /></p>
</form>

<?php
$goodCredit = $score >= 680;

if($goodCredit == true):
    echo "Decision: The loan is approved";
else:
    echo "Decision: The loan is denied";
endif;

echo "</div>";
?>

Previous Copyright © 2015-2022, FunctionX Next