Branching Structures

Control structures include branching structures, which allow your program to make all these things:

  • if. . .then decisions

  • Loops, which let you execute some code repeatedly

  • Functions that put specialized code into their own separate section

When you run a program, you expect it to go from beginning to end. Usually, the program displays everything that is in the code, putting each section one after another. When you write an HTML page, every part of the page is displayed in the same order as it is defined in the source. However, you might want to change that flow. You might need to perform a different action because some special event occurs. PHP offers a way to do this with branching structures.

if

The easiest way is to use the if branching structure. A basic backbone looks like the following:

if (condition is true)
{
//execute statements
}

You obviously need to replace the comparison with a condition test. Condition tests are done using the comparison operators, such as <, >, !=, and so on. Take a look at Chapter 5 to see the comparison methods.

We will create a page that allows a user to enter two numbers, and we use PHP to compare the two numbers and say which is bigger. First, let’s take a look at the form that would do this. We are going to use the GET submit method.

<html>

<head>
<title>Comparing two numbers</title>
</head>

<body>


<form name="compare" action="phpft07-01.php" method="get">

       Enter your first number: <input type="text" name="firstnumber">
       <br />Enter your second number: <input type="text" name="secondnumber">
       <br /><br /><input type="submit">
</form>

</body>

</html>

This page ends up looking like Figure 7.1. I added the numbers into the textbox after opening the page.

Figure 7.1. The phpft07-01.html form file.


Now look at the PHP page:

<html>

<head>
<title>Comparison of two numbers</title>
</head>
<body>
<?php

$a = $_GET['firstnumber'];
$b = $_GET['secondnumber'];

echo "Your first number was $a.";
echo "<br>Your second number was $b.";
echo "<p>";

if ($a > $b)
{
    echo "Your first number ($a) is greater than your second number ($b).";
}

if ($a < $b)
{
    echo "Your second number ($b) is greater than your first number ($a).";
}
?>

</body>
</html>

You see how this page works? Figure 7.2 shows what it looks like.

Figure 7.2. The phpft07-01.php results file.


A couple if statements work together to determine whether the first number is larger than the second or vice versa. If the first one is greater, that is echoed, and if the second is greater than the first, the correct result is echoed. However, what happens if the numbers are equal? Check it out in Figure 7.3.

Figure 7.3. The form with equal values.


If the numbers are equal, nothing happens! We did not set up the program to do anything if this situation occurs. We obviously need to fix this.

else

Let me show you a new control structure that works tightly with the one you already know: else. When you join an if structure to an else structure, one of the two statements will be executed. If the comparison test is true, the if statements are executed, and if the test is false, the else statements are executed.

Look at a generalized else structure:

if (comparison is true)
{
//execute statements
}
else
{
//execute other statements
}

Let’s try putting this into our file, with phpft07-02.php. (I copied over the HTML file for the CD as well, with the only change being the form action.)

if ($a > $b)
{
    echo "Your first number ($a) is greater than your second number ($b).";
}
else
{
    echo "Both your first number ($a) and your second number ($b) are equal!.";
}
if($a < $b)
{
   echo "Your second number ($b) is greater than your first number ($a).";
}
else
{
   echo "Both your first number ($a) and your second number ($b) are equal!.";
}

This makes sense, right? If the tests are false, it echoes out that the numbers are equal. However, we just created a couple of big problems. Try to see if you can find them, then check out Figure 7.4. Now it should be easier to spot the problem within the code.

Figure 7.4. Using phpft07-02.php with some errors.


You see here that it actually gives two results! The code is going through both structures. For the first structure, it checks to see if $a is greater than $b. This is not true, so it executes the else statements. Therefore, the first text written is that the two numbers are equal. Next, the code goes to the second if statement, where it determines that $a is indeed bigger than $b. Because the if control structure rings true, it executes the if statements and says that the second number is bigger than the first one.

Before we move on, let’s see what happens when you put in two equal numbers. The result is Figure 7.5.

Figure 7.5. Using phpft07-02.php with equal numbers.


Here, you can see that neither the first if or second structure is true. Because of this, both execute their second statements, ending up with two comments saying that the numbers are equal. We need to fix this so it only shows once and doesn’t give the wrong answer every time.

elseif

We need to figure out a way to put if statements together so we can use the else command and not have to execute the same code twice. Fortunately, PHP provides a control structure called elseif, which is very similar to if. It is part of an if structure and only executes on two conditions: First, the if test needs to fail and second, its own elseif test needs to succeed. Check out the basic structure:

if (comparison is true)
{
//execute statements
}
elseif (different comparison is true)
{
//execute other statements
}

You can add an else section to this control structure as well, which only executes if both the if and the elseif sections fail. Let’s put the two if sections together on the page and add the else. This allows us to finally have a well-designed structure that gives no errors.

if ($a > $b)
{
    echo "Your first number ($a) is greater than your second number ($b).";
}
elseif ($a < $b)
{
    echo "Your second number ($b) is greater than your first number ($a).";
}
else
{
    echo "Both your first number ($a) and your second number ($b) are equal!.";
}

This structure can have only three possibilities. $a could be bigger than $b, $b could be bigger than $a, or they could be equal. However, only one of the three echo statements will be executed.

Caution

Take note that this page only deals with integers. If you enter a string rather than a number, you might get some erratic results.


Note

One other branching structure is the ternary structure, which is very similar to if. . .else. You can see some more examples with the ternary operator in Chapter 5.


switch

switch is excellent at comparing one variable to several possible values. switch only works when checking to see if an input is exactly the same as a value; you cannot run comparison tests on it. This is a great way to compare a variable against several different known values to see if something occurs. For example, you can see if $a equals 0 or a, but you cannot use switch to see if $a is greater than $b. The following is the generalized structure for a switch statement:

switch($variable)
{
   case 0:
         //execute statements
         break;
   case 1:
         //execute statements
         break;
   default:
         //execute statements only if none of the cases fit
         break;
}

Let’s quickly recreate a program we did earlier. Remember when I introduced if control structures while designing the calculator? Let’s go back to that and use switch instead of if. The HTML file is the same, except the action attribute has changed; the PHP file has changed. Check out what it now looks like. This file is phpft07-04.php on the CD. Figure 7.6 shows you what the form page looks like.

Figure 7.6. The phpft07-04.html form file.


<?php
//Put $_GET variables into our own variables
$a = $_GET['first'];
$b = $_GET['second'];
$op = $_GET['operation'];

echo "The result of your expression, $a $op $b is ";
//Echo out the result of the chosen operation
switch ($op)
{

case '+':
        echo $a + $b;
        break;

case '-':
        echo $a - $b;
        break;

case '*':
        echo $a * $b;
        break;

case '/':
        echo $a/$b;
        break;

case '%':
        echo $a%$b;
        break;

default:
        echo "Warning: Operation Not Valid";
        break;

}

?>

This replaces it all with switch, including a default value just in case the user enters something that gives a big error. One result might look like Figure 7.7.

Figure 7.7. The phpft07-04.php file.


You might be wondering what the break statements do. switch is designed so that the execution of one of the commands will flood into another one. So, for example, if we removed the breaks and did an addition problem on our calculator, we would get six results: the addition, the subtraction, the multiplication, the division, the modulus, and the default echo. break stops this by exiting directly out of the switch structure. As a general rule, always use a break after each case unless there is an overbearing reason not to do so.

It’s important to note that I included a default case for the switch statement, even though it appears impossible for the operation to ever be anything other than the given choices. However, you should always include a default clause for your switch statement. What if the form is a GET form and the user changes the operation through the URL? Other things can come up that may confuse your program, so it is always better to be safe and simply use a default clause.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.70.203