Home

Conditionally Switching

Fundamentals of Switches

Introduction

Imagine you have an expression that involves many if or elseif conditions. Here is an example:

<?php
echo "<div style='width: 300pt; margin: auto;'>
<form name='frmPayrollPeriod' method='post'>
<table>
  <tr>
    <td>Weekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='1'></input></td>
  </tr>
  <tr>
    <td>Biweekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='2'></input></td>
  </tr>
  <tr>
    <td>Semimonthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='3'></input></td>
  </tr>
  <tr>
    <td>Monthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='4'></input></td>
  </tr>
  <tr>
    <td>Biweekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='5'></input></td>
  </tr>
  <tr>
    <td>Semimonthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='6'></input></td>
  </tr>
  <tr>
    <td>Monthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='7'></input></td>
  </tr>
</table>

<input type='submit' name='btnSubmit' value='Submit' />
</form>";

$period = htmlspecialchars($_POST['rdoPayrollPeriod']);

if($period == 1)
    echo "Payroll Period: Weekly<br>";
elseif($period == 2)
    echo "Payroll Period: Biweekly<br>";
elseif($period == 3)
    echo "Payroll Period: Semimonthly<br>";
elseif($period == 4)
    echo "Payroll Period: Monthly<br>";
elseif($period == 5)
    echo "Payroll Period: Quarterly<br>";
elseif($period == 6)
    echo "Payroll Period: Semiannually<br>";
elseif($period == 7)
    echo "Payroll Period: Annually";

echo "</div>";
?>

When this code executes, each condition would be checked from top to bottom. PHP (like many languages) provides a shortcut so that the PHP interpreter would jump directly to the only condition with which it is concerned. This is done using a keyword named switch. The primary formula to use it is:

switch(value)
{
    case value1:
        expression1;
    case value2:
        expression2;
    case value_n:
        expression_n;
}

You start with the required switch keyword and its parentheses. The switch conditional statement must be delimited. This is usually done using curly brackets. The opening curcly bracket can be written on the same line or the next line of the switch line. Here is an example:

switch(value):

endswitch

An alternative is to use a colon in place of the opening curly bracket and use the endswitch keyword in place of the closing curly bracket. Here is an example:

switch(value):

endswitch

In the parentheses of the switch conditional statement, specify a value by which each condition will be checked. This can be the name of a variable that holds the value or an expression that produces a constant value.

In the body of the conditional statement, create each possible value to compare to the value in the parentheses. Each internal value is specified with, or preceded by, the case keyword. The value is followed by a colon. The section after the colon to the next case is referred to as its body. The body of the last case is from its colon to the closing of the switch conditional statement. In the body of each case, create the desired statement. The statement(s) must end with a semicolon. Here is an example:

<?php
echo "<div style='width: 200pt; margin: auto;'>
<form name='frmPayrollPeriod' method='post'>
<table>
  <tr>
    <td>Weekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='1'></input></td>
  </tr>
  <tr>
    <td>Biweekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='2'></input></td>
  </tr>
  <tr>
    <td>Semimonthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='3'></input></td>
  </tr>
  <tr>
    <td>Monthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='4'></input></td>
  </tr>
  <tr>
    <td>Biweekly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='5'></input></td>
  </tr>
  <tr>
    <td>Semimonthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='6'></input></td>
  </tr>
  <tr>
    <td>Monthly</td>
    <td><input type='radio' name='rdoPayrollPeriod' 
                            value='7'></input></td>
  </tr>
</table>

<input type='submit' name='btnSubmit' value='Submit' />
</form>";

$period = htmlspecialchars($_POST['rdoPayrollPeriod']);

switch($period){
    case 1:
        echo "Payroll Period: Weekly<br>";
    case 2:
        echo "Payroll Period: Biweekly<br>";
    case 3:
        echo "Payroll Period: Semimonthly<br>";
    case 4:
        echo "Payroll Period: Monthly<br>";
    case 5:
        echo "Payroll Period: Quarterly<br>";
    case 6:
        echo "Payroll Period: Semiannually<br>";
    case 7:
        echo "Payroll Period: Annually";
}
echo "</div>";
?>

Here is an example of using the webpage:

Fundamentals of Switches

Fundamentals of Switches

Here is another example of using the webpage:

Fundamentals of Switches

Fundamentals of Switches

Here is another example of using the webpage:

Fundamentals of Switches

Fundamentals of Switches

Breaking/Continuing a Case

In the above case, notice that whenever a case is selected, all cases under it are visited. This is usually not the desired behavior. To make sure that only the desired case is visited, you can (should, must) end its body with the break or the continue keyword. Based on this, the primary formula of the switch conditional statement is:

switch(value {
    case value1:
        expression1
        break | continue;
    case value2:
        expression2
        break | continue;
    case value_n:
        expression_n
        break | continue;
}

By breaking each case, our code can be written as follows:

<?php
. . .

$period = htmlspecialchars($_POST['rdoPayrollPeriod']);

switch($period):
    case 1:
        echo "Payroll Period: Weekly";
        break;
    case 2:
        echo "Payroll Period: Biweekly";
        break;
    case 3:
        echo "Payroll Period: Semimonthly";
        contunue;
    case 4:
        echo "Payroll Period: Monthly";
        break;
    case 5:
        echo "Payroll Period: Quarterly";
        continue;
    case 6:
        echo "Payroll Period: Semiannually";
        break;
    case 7:
        echo "Payroll Period: Annually";
        break;
endswitch;
echo "</div>";
?>

(In this case, the break or the continue keyword can be omitted from the last case) Here is an example of using the webpage:

Fundamentals of Switches

Fundamentals of Switches

Here is another example of using the webpage:

Fundamentals of Switches

Fundamentals of Switches

If There is no Match: The Default Case

Depending on the conditional statement, it is posible that no case will match the switch value. You should indicate what to do if that happens. To assist you with this, PHP provides the default keyword that you can use as one of the cases. If the default case is in a position other than the last, it should (must) end with the break keyword. Here is an example:

<?php
echo "<div style='width: 200pt; margin: auto;'>
<form name='frmPayrollPeriod' method='post'>
<p>Type a number between 1 and 7: 
   <input type='text' name='txtPayrollPeriod'></input></p>
   <input type='submit' name='btnSubmit' value='Submit' />
</form>";

$period = htmlspecialchars($_POST['txtPayrollPeriod']);

switch($period)
{
    default:
        echo "Payroll Period: Miscellaneous";
        break;
    case 1:
        echo "Payroll Period: Weekly";
        break;
    case 2:
        echo "Payroll Period: Biweekly";
        break;
    case 3:
        echo "Payroll Period: Semimonthly";
        break;
    case 4:
        echo "Payroll Period: Monthly";
        break;
    case 5:
        echo "Payroll Period: Quarterly";
        break;
    case 6:
        echo "Payroll Period: Semiannually";
        break;
    case 7:
        echo "Payroll Period: Annually";
        break;
}
echo "</div>";
?>

Here is an example of using the webpage:

The Default Case

The Default Case

The Default Case

The Default Case

If the default case is the last option, it doesn't need a break (but you can add it if you want).

Characteristics of a Switch

The Types of Case Values

There are various types of values a switch conditional statement can use. It can be an integer as in the above example. It can be a symbol or an alphabetical letter. Here is an example:

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

$grade = htmlspecialchars($_POST['txtGrade']);
?>
<form name="frmGrade" method="post">
<p>Enter the student letter grade (A, B, C, D, etc): 
   <input type="text" name="txtGrade" style="width: 40px" value="

<?php echo $grade ?>

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

<?php
switch($grade)
{
    case 'A':
        echo "Decision: Pass";
        break;
    case 'B':
        echo "Decision: Pass";
        break;
    case 'C':
        echo "Decision: Pass";
        break;
    case 'D':
        echo "Decision: Fail";
        break;
    case 'F':
        echo "Decision: Fail";
        break;
    case 'I':
        echo "Decision: Insufficient";
        break;
    case 'W':
        echo "Decision: Withdraw";
        break;
    default:
        echo "Decision: Not Available";
        break;
}
echo "</div>";
?>

Here is an example of using the webpage:

The Types of Case Values

The Types of Case Values

The Types of Case Values

The value can be a string, Here is an example:

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

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

<?php
echo "<form name='frmPayroll' method='post'>
      <div id='formulation'>
      <p id='main-title'>Employee Payroll</p>";

      $withhodingAllowance = 0.00;

      $payrollFrequency = htmlspecialchars($_POST['cbxPayrollFrequency']);
      $wagePayment   = htmlspecialchars($_POST['txtWagePayment']);
      $exemptions    = htmlspecialchars($_POST['txtExemptions']);

      $allowances = $allowance * $exemptions;
      $primaryTaxableGrossWages = $wagePayment - $allowances;

      // https://www.irs.gov/pub/irs-pdf/p15.pdf
      switch($payrollFrequency)
      {
          case "Weekly":
              $withhodingAllowance = 76.90;
              break;
          case "Biweekly":
              $withhodingAllowance = 153.80;
              break;
          case "Semimonthly":
              $withhodingAllowance = 166.70;
              break;
          case "Monthly":
              $withhodingAllowance = 333.30;
              break;
          case "Quarterly":
              $withhodingAllowance = 1000.00;
              break;
          case "Semiannually":
              $withhodingAllowance = 2000.00;
              break;
          case "Annually":
              $withhodingAllowance = 4000.00;
              break;
          default:
              $withhodingAllowance = 15.40 * 5.00;
      }

echo "      <table border='4'>
        <tr>
          <td>Payroll Frequency:</td>
          <td>
	    <select name='cbxPayrollFrequency'>
              <option>&nbsp;</option>
              <option>Weekly</option>
              <option>Biweekly</option>
              <option>Semimonthly</option>
              <option>Monthly</option>
              <option>Quarterly</option>
              <option>Semiannually</option>
              <option>Annually</option>
            </select>
	    <input name='Submit' type='submit' value='Evaluate' />
	     </td>
        </tr>
        <tr>
          <td>Withholding Allowance:</td>
          <td><input name='txtWithholdingAllowance' type='text' value='$withhodingAllowance ' /> </td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of using the webpage:

The Types of Case Values

The Types of Case Values

The Types of Case Values

The value can be a Boolean value.

Combining Cases

If a conditional switch has more than one case that have the same outcome, you can combine those cases. To do this, create each of the cases without its body, except for the last that must include the statement body. Here are two examples:

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

$grade = htmlspecialchars($_POST['txtGrade']);
?>
<form name="frmGrade" method="post">
<p>Enter the student letter grade (A, B, C, D, etc): 
   <input type="text" name="txtGrade" style="width: 40px" value="

<?php echo $grade ?>

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

<?php
switch($grade)
{
    case 'A':
    case 'B':
    case 'C':
        echo "Decision: Pass";
        break;
    case 'D':
    case 'F':
        echo "Decision: Fail";
        break;
    case 'I':
        echo "Decision: Insufficient";
        break;
    case 'W':
        echo "Decision: Withdraw";
        break;
    default:
        echo "Decision: Not Available";
        break;
}
echo "</div>";
?>

Here is an example of using the webpage:

Combining Cases

Combining Cases

Combining Cases

Options on Creating and Using Switches

Matching a Conditional Statement

As mentioned above, you can create a conditional swicth that matches a Boolean value of true or false. Instead of a simple Boolean value, you can create a Boolean expression as the value. In this case, the options to compare would be true and false. 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
switch($score >= 680):
    case true:
        echo "Decision: The loan is approved";
        break;
    case false:
        echo "Decision: The loan is denied";
        break;
endswitch
?>

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

Here is an example of using the webpage:

Matching a Conditional Statement

Matching a Conditional Statement

The expression can be as complex as you want. The expression can be a Boolean disjunction or conjunction. To consider the opposite to the value to match, precede it with the ! operator.

Nesting a Conditional Statement in a Switch

A conditional statement (if. elseif, and else) can be created in the body of a case of another conditional switch. In the same way, the statement can involve Boolean conjunctions or disjunctions. This is referred to as nesting. Here are examples:

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

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

<?php
echo "<form name='frmPayroll' method='post'>
      <div id='formulation'>
      <p id='main-title'>Employee Payroll</p>";

      $allowance      = 76.90;
      $withheldAmount = 0.00;

      $maritalStatus = htmlspecialchars($_POST['cbxMaritalsStatus']);
      $wagePayment   = htmlspecialchars($_POST['txtWagePayment']);
      $exemptions    = htmlspecialchars($_POST['txtExemptions']);

      $allowances = $allowance * $exemptions;
      $taxableGrossWages = $wagePayment - $allowances;

      // https://www.irs.gov/pub/irs-pdf/p15.pdf
      switch($maritalStatus){
          case "Single":
              if(     $taxableGrossWages <=  44.00)                                     $withheldAmount =                                                       0.00;
              elseif(($taxableGrossWages >   44.00) && ($taxableGrossWages <=  222.00)) $withheldAmount =            ($taxableGrossWages -   44.00) * 10.00 / 100.00;
              elseif(($taxableGrossWages >  222.00) && ($taxableGrossWages <=  764.00)) $withheldAmount =   17.80 + (($taxableGrossWages -  222.00) * 15.00 / 100.00);
              elseif(($taxableGrossWages >  764.00) && ($taxableGrossWages <= 1789.00)) $withheldAmount =   99.10 + (($taxableGrossWages -  764.00) * 25.00 / 100.00);
              elseif(($taxableGrossWages > 1789.00) && ($taxableGrossWages <= 3685.00)) $withheldAmount =  355.35 + (($taxableGrossWages - 1789.00) * 28.00 / 100.00);
              elseif(($taxableGrossWages > 3685.00) && ($taxableGrossWages <= 7958.00)) $withheldAmount =  886.23 + (($taxableGrossWages - 3685.00) * 33.00 / 100.00);
              elseif(($taxableGrossWages > 7958.00) && ($taxableGrossWages <= 7990.00)) $withheldAmount = 2296.32 + (($taxableGrossWages - 7958.00) * 35.00 / 100.00);
              else                                                                      $withheldAmount = 2307.52 + (($taxableGrossWages - 7990.00) * 39.60 / 100.00);
              break;

          case "Married":
              if(     $taxableGrossWages <= 165.00)                                     $withheldAmount =                                                       0.00;
              elseif(($taxableGrossWages >  165.00) && ($taxableGrossWages <=  520.00)) $withheldAmount =            ($taxableGrossWages -  165.00) * 10.00 / 100.00;
              elseif(($taxableGrossWages >  520.00) && ($taxableGrossWages <= 1606.00)) $withheldAmount =   35.50 + (($taxableGrossWages -  520.00) * 15.00 / 100.00);
              elseif(($taxableGrossWages > 1606.00) && ($taxableGrossWages <= 3073.00)) $withheldAmount =  198.40 + (($taxableGrossWages - 1606.00) * 25.00 / 100.00);
              elseif(($taxableGrossWages > 3073.00) && ($taxableGrossWages <= 4597.00)) $withheldAmount =  565.15 + (($taxableGrossWages - 3073.00) * 28.00 / 100.00);
              elseif(($taxableGrossWages > 4597.00) && ($taxableGrossWages <= 8079.00)) $withheldAmount =  991.87 + (($taxableGrossWages - 4597.00) * 33.00 / 100.00);
              elseif(($taxableGrossWages > 8079.00) && ($taxableGrossWages <= 9105.00)) $withheldAmount = 2140.93 + (($taxableGrossWages - 8079.00) * 35.00 / 100.00);
              else                                                                      $withheldAmount = 2500.03 + (($taxableGrossWages - 9105.00) * 39.60 / 100.00);
              break;
          default:
              $withheldAmount = 0.00;
      }

      $netPay = $taxableGrossWages - $withheldAmount;

echo "      <table border='4'>
        <tr>
          <td>Marital Status:</td>
          <td>
	    <select name='cbxMaritalsStatus'>
              <option>&nbsp;</option>
              <option>Single</option>
              <option>Married</option>
            </select></td>
        </tr>
        <tr>
          <td>Wage Payment:</td>
          <td>
	    <input name='txtWagePayment' type='text' value='$wagePayment' /></td>
        </tr>
        <tr>
          <td>Exemptions:</td>
          <td>
	    <input name='txtExemptions' type='text'
                   style='width: 60px' value='$exemptions' />
	    <input name='Submit' type='submit' value='Calculate' />
          </td>
        </tr>
        <tr>
          <td>Allowances:</td>
          <td>
	    <input name='txtAllowances' type='text'
                   style='width: 60px' value='$allowances' />
          </td>
        </tr>
        <tr>
          <td>Taxable Gross Wages:</td>
          <td><input name='txtTaxableGrossWages' type='text' value='$taxableGrossWages' /></td>
        </tr>
        <tr>
          <td>Tax Withheld:</td>
          <td>
	    <input name='txtTaxWithheld' type='text' value='$withheldAmount' /></td>
        </tr>
        <tr>
          <td>Net Pay:</td>
          <td>
	    <input name='txtNetPay' type='text' value='$netPay' /></td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of using the webpage:

Nesting a Conditional Statement in a Switch

Nesting a Conditional Statement in a Switch

Here is another example of using the webpage:

Nesting a Conditional Statement in a Switch

Nesting a Conditional Statement in a Switch

In the same way, you can nest a conditional statement that itself is nested in a matching pattern that itself is nested in another conditional statement or in another matching pattern, etc.


Previous Copyright © 2015-2022, FunctionX Next