PHP Logo

Chapter 3 - Selection Control Structures

By: Albert Ritzhaupt

 

 


Chapter Topics 

Relational Operators 

Computers can be programmed to make decisions.  These decisions are conditions that can be evaluated to either true or false.  In this section, we will explore the syntax for making decisions using PHP, but first we must spend some time learning the different relational operators.  The table below shows the different relational operators available to you in PHP (Developer Fusion, 2005).

Operator Description
< Less than (eg. $x < 10).
<= Less than or equal (eg. $x <= 10).
== Equivalence (eg. $x == 10).
> Greater than (eg. $x > 10).
>= Greater than or equal (eg. $x >= 10).
!= Not equivalent (eg. $x != 10).

Most of you are familiar with all of these operators from an algebra course at some point in your academic career.  The relational operators are extremely important for you to understand.  A few other important things for you to notice are: (1) the equals sign in PHP is (==) two equals signs rather than one (assignment), and (2) an exclamation point followed by one equals sign (!=) is not equals.  Try to remember these points because it catch up with you later if you don't.

back to top

PHP If Statement

The if-statement is extremely useful in web programming.  This control structure will allow you to make decisions.  The If-statement syntax is quite simple for you to remember and is shown in the figure below.  If condition evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE, it will not execute.

if(condition)
{
statement
}

Although the syntax above shows only one statement, it is possible to add any number of statements.  To make sure you understand how the if-statement works, let's try a couple examples.  The table below provides a few.

Example Explanations
$a=10;
$b=10;
if ($a == $b)
{
   echo "True";
}
This example uses two integers.  The result of this selection statement is True because both $a and $b hold the value 10, and the relational operator is equals.  Therefore, true is printed using the echo statement.
$a=10;
$b=10;
if ($a >= $b)
{
   echo "True";
}
This example also uses two integers. The result of this selection statement is True both $a and $b hold the value 10, and the relational operator is greater than or equal to.  Therefore, true is printed using the echo statement.
$a="Bob";
$b="Carol";
if ($a == $b)
{
   echo "True";
}
This example uses two string variables.  $a is assigned the string literal "Bob" and $b is assigned "Carol".  The equals relational operator is used, and since "Bob" is not equal to "Carol", the statement does not execute.
$a="Bob";
$b="Carol";
if ($a != $b)
{
   echo "True";
}
This example uses two string variables. Both $a and $b are assigned the same values as in the previous example.  This time, the (!=) operator is used, and the statement is therefore executed.

Now that you have some experience with the if-statement in its simplest form, we can discuss more complicated topics.  The if-statement in the example above only evaluated one statement.  However, the if statement can be used to evaluate many statements.  Let's first try evaluating two statements using the if-else statement, which is a simple extension to the if-statement.  The if-else statement syntax can be seen in the figure below.

if (condition)
{
statement 1
}else{
statement 2
}

The if-else statement in its simplest form will evaluate two statements.  If the condition is true, statement 1 will be executed.  If the condition is false, statement 2 will execute.  Regardless of whether the condition is true or false, one of the statements will execute.  This is fundamentally different than the examples before, when only one statement executed.  TO make sure you understand, look at the following examples.

Example Explanations
$a=10;
$b=10;
if ($a > $b)
{
   echo "True";
}else{
   echo "False";
}
This example uses two integers.  The result of this selection statement is False because both $a and $b hold the value 10, and the relational operator is greater than.  10 is not greater than 10.  Therefore, False is printed using the echo statement.
$a=10;
$b=10;
if ($a >= $b)
{
   echo "True";
}else{
   echo "False";
}
This example uses two string variables.  $a is assigned the string literal "Bob" and $b is assigned "Carol".  The not equals relational operator is used, and since "Bob" is not equal to "Carol", the first statement executes resulting in True being outputted.

There is one more extension to the if statement that you need to be aware of, the "elseif" statement.  The elseif statement extends the number of conditions in the if control structure.  The syntax can be seen in the figure below.

if (condition)
{
statement 1
}elseif (condition){
statement 2
}

The elseif statement is a handy tool when two or more conditions need to be evaluated.  For a solid example, consider a grading scale as shown in the diagram below.

Grading Scale and Code Explanations
A - (90 - 100)
B - (80 - 89)
C - (70 - 79)
D - (60 - 69)
F - (0 - 59)
A grading scale is shown to the left.  There are five letter grades or conditions to be evaluated, each with a numeric grade range.  The goal of the program is to take a numeric grade and evaluate the corresponding letter grade.
$a=75;
$b="";
if ($a >= 90){
   $b = "A";
}elseif ($a >= 80){
   $b = "A";
}elseif ($a >= 70){
   $b = "A";
}elseif ($a >= 60){
   $b = "";
}else{
   $b = "F";
}
echo "The letter grade is $b";
As you can see here, the elseif statement is used to evaluate every letter grade except the first and the last.  The first uses the traditional if statement and the last uses the else for the range of 0 - 69.

There are some important things to remember as it relates to using the elseif statement.  You must use the if statement first, and the else statement must always be the last condition, if used.  If the else statement is not used, there is the possibility that none of the statements will be executed.

back to top

Logical Operators

Now that you understand the  syntax of the if statement and its extensions, we can explore the logical operators available to you in PHP.   In the English language, we use logical conjunctions (and, or, etc.) to connect ideas.  For example, if one was to say "if it does not rain today and the traffic is good, I will go to the beach," the logical conjunction "and" connects "it does not rain" and "the traffic is good".  In order for this individual to go to the park (the action or statement), two conditions must be true: it must not rain and the traffic must be good.  Just as we can connect conditions in the English language, PHP supports logical operators to connect conditions in programming.  The table below shows the different logical operators.

Operator Description
! (not) $x=12;
if(!($x < 10)){
    $x=5;
}
echo $x;
Output: 5
&& (and) $x=7;
if($x < 10 && $x > 5){
    $x=5;
}
echo $x;
Output: 5
|| (or) $x=10;
if($x < 10 || $x > 5){
    $x=5;
}
echo $x;
Output: 5

The first operator is the not operator.  The not operator takes the inverse of the value.  For instance, in the example above, the variable $x is not less than 10; therefore, the condition is true and the statement is executed.  In the second example, the and operator is used.  The and operator logically connects two independent conditions.  When the and operator is used, both of the conditions must be true.  In the example, the variable $x is less than 10 and greater than 5; therefore, the condition is true and the statement is executed.  The final example shows the logical or operator.  When the or operator is used, only one of the statements must be true in order for the condition to be true.  Keep in mind that the order of operations also applied to logical operators (Not, And, Or).

back to top

Working with Nested Ifs

We have seen that the if statement and its extensions are extremely useful to a programmer in the examples above.  However, in all the examples above, we have only one if statement in use.  It is possible to nest if statements to achieve more sophisticated logic.  The term next means that once occurs within another.  Look at the figure below for a simple example:

if(condition1)
{
 if(condition2)
{
statement
}
}

The generic syntax above shows that one if statement is within another if statement.  One could nest deeper, if necessary.  In this example, for the statement to execute, both condition1 and condition2 must be true.  If condition1 was false, condition2 would never be checked.  It is also important to notice that the statements are successively indented.  The indentation is not a requirement, but for readability purposes, it is recommended that you indent deeper logic.

back to top

PHP Switch and Break Statement

Another type of the selection control structure available to you in PHP is the switch statement.  The switch statement is similar to a series of if statements as shown in the grading scale example above.  However, the requires that  statement the data type be the same for each of the conditions.  To illustrate the switch statement, look at the example below.

Example Explanations
$x=2;
switch ($x) {
case 0:
   echo "x equals 0"; 
   break;
case 1:
   echo "x equals 1";
   break;
case 2:
   echo "x equals 2";
   break;
default:
   echo "unknown";
}
In this example, the variable $x is assigned the value 2.  The switch statement checks to see if the value is 0, then 1, then 2.  In the case statement, order matters.  Since the value of $x is case 2, the code directly after the statement is executed.  Also, notice the break statement directly after the echo statements.  If the break statement is not placed there, the flow of control would not exit the control structure and the code following would be executed.

The switch statement has a limitation.  When using a series of if statements, a different data type and variable could be compared at each condition.  When using the switch statement, only one variable is intended to be used. 

back to top

Capturing POST and GET

As briefly mentioned in chapter 1, a PHP program will often use information provided by a user.  This information is sent to a PHP program by using an HTML form.  In a PHP program, one must first capture the information before it can be used.  The example below shows the code for a simple form in HTML:

<html>
<form action="process3.php" method="GET">
Your Name: <input type="text" name="yName"><br>
<input type="Submit" value="Send Name">
</form>
</html>

Notice that there is one textbox control with the name "yName".  Also notice that the action points to a PHP file in the current directory using the GET method.  As previously mentioned, the GET method passes the values as part of the URL in a process known as URL encoding.  Now assume that the process.php file contains the following:

<html>
<?php
$yName=$_GET['yName'];
echo "Your name is $yName";
 ?>
</html>

The $_GET['yName'] captures the value of the yName control on the HTML form.  After the variable is captured, it is printed using the echo statement.  The link below is to this program.  Put your name in the textbox and press Send Name.  Notice that the name is visible as part of the URL.  To capture information using the POST method, use $_POST[].

>>Program Example

back to top

Your Third Program

This section will provide the steps for you to create your third PHP program.  You are going to create a number guessing game. 

  1. First create a file named "third.html" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <h3>Guess a number between 1 and 20</h3>
    <form action="program3.php" method="post">
    Your Guess: <input name="guess"><br>
    <input type="Submit" value="Guess!">
    <input type="hidden" name="tries">
    </form>

    </html>

  2. Now let's create the source code for the program.  Create a file named "program3.php" in the same directory as "third.html".  The file should contain the following information:

    <html>
    <h3>Guess a number between 1 and 20</h3>
    <?php
    //captures variables
    $tries=$_POST['tries'];
    $guess=$_POST['guess'];
    $tries = $tries + 1;
    //if statement
    if ($guess == 10){
    echo "$guess is correct.<br>";


    echo "It took you $tries tries<br>";
    echo "<a href='third.html'>Try Again</a><br>";
    }elseif ($guess < 10){
    echo "No, higher than $guess.<br>";
    echo "This is your $tries try.<br>";
    }else{
    echo "No, lower than $guess.<br>";
    echo "This is your $tries try.<br>";
    }
    ?>
    <br><br>
    <form action="program3.php" method="post">
    Your Guess: <input name="guess"><br>
    <input type="Submit" value="Guess!">
    <input type="hidden" name="tries" value="<?php echo $tries; ?>">
    </form>

    </html>

    Note:  The source code must appear exactly as it does here.  Otherwise, you will likely run into syntax errors. 
  3. After you have created the file and put the information into the files, save your work, and change the permissions of the files to:

    prompt$: chmod 704 third.html
    prompt$: chmod 705 program3.php

  4. Open the URL to the location where you saved the file (third.html) and you should be able to play the number game.

    Pay special attention to the logic of the if statement.  If the guess is not equal to 10, then the next condition is checked.  If the guess is not less than 10, then the else clause is automatically executed.  If it makes it to the else clause, it is assumed that the

Congratulations! You have completed the third chapter. You can now take the online assessment, complete the third activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 3

Create a simple HTML form with the title "Calculate Letter Grade".  This form should accept the grades as textboxes for four quizzes (titled Quiz 1, Quiz 2, etc), three assignments (titled Assignment 1, Assignment 2, etc), Mid term Exam, and Final Exam.   Be sure to properly name each of the controls and place a submission button.  Now, you are going to create a program to calculate the letter grade based on the information provided in the form.    Set the action to point to a file named "calcGrade.php" and to the POST method.

Create another file named "calcGrade.php".  The program should calculate the letter grade using the following weighting scale: (30%) assignments, (30%) quizzes, (20%) mid term exam, and (20%) final exam.  Your algorithm should take the following steps:

1.  Capture the grades from the HTML form.
2.  Calculate the numeric grade weighted as shown above.
3.  Use a selection control structure to take the numeric grade and map it to the corresponding letter grade.  The grading scale is shown below.

A - (90 - 100)
B - (80 - 89)
C - (70 - 79)
D - (60 - 69)
F - (0 - 59)

back to top

Chapter References 

back to top

Previous section Next section

 

Copyright Albert Dieter Ritzhaupt. All Rights Reserved.