Search This Blog

Tuesday, February 16, 2010

Conditional or Branching Statements

In its simplest form, a conditional piece of code means either "execute one line of code" or "don't execute it at all," depending on whether a specified criterion is met. A more complex variation is to either "execute this line of code" or "execute that line of code" depending on which condition is met. You can extend this to execute one complete section of code, or execute another complete section of code. Finally, it's possible to list a whole heap of possible outcomes to a certain condition. If the result of the condition is outcome number 1, then execute section 1 of code; if the result is outcome number 2, then execute section 2; if the result is outcome number 3 then execute section number 3, and so on.

An Example of Branching

So far this is a rather abstract discussion, so perhaps an example from day-to-day life would be helpful. Shopping is a fairly mundane activity but it works rather well in illustrating the type of decision-making your program might have to perform.


Imagine that you have to compile a list of items that you will need to make a cheese sandwich for your lunch. You'll have to check to see if there are any items you need to make the sandwich and go with your lunch, and buy them at the store if necessary. Here's the process:
  • Check the fridge to see if you have milk, cheese, and butter.
  • If you don't, add what's missing to your grocery list and proceed; if you have everything, proceed.
  • Check the bread bin to see if you have any bread.
  • If you haven't, add bread to your list and proceed; if you have, proceed.
  • If you already have all of the items needed, make a cheese sandwich; if not, proceed.
  • Go to the supermarket.
  • Buy the items you need.
  • Make a cheese sandwich.
This example represents just a small portion of the logical decision-making process that you use as you make your way through each day. You often check for certain conditions (do you have the necessary food items) before taking certain steps (such as making a sandwich), and depending on the conditions (you're out of cheese), you may take more steps (such as going to the store and buying food) to accomplish your objective (such as making a cheese sandwich).
The example is typical of decision-making statements in PHP. When you write PHP programs, parts of the code are written to deal with specific situations and if a particular situation doesn't arise, then there is no need to run the PHP code that relates to it.


You could actually represent this example's entire process quite easily with a PHP program. In fact, the statements in the example are close enough to what you need that you could use them as pseudo code (they would actually fit most programming languages pretty well because this kind of decision-making process can be represented in most programming languages with if statements).


For example, you could write the following code in PHP, assuming you have variables named $fridge and $bread_bin that hold string values consisting of the items in them:


if ($fridge == "milk and cheese and butter") {
     if ($bread_bin == "bread") {
        make_sandwich();
     } else {
        go_to_store();
        make_sandwich();
     }
} else {
   go_to_store();
     make_sandwich();
}

In other words, if the fridge has milk and cheese and butter, then check to see if the bread bin has bread. If both these conditions are true, stay home and make your sandwich. If the bread bin has no bread, however, you must go to the store and get some before you can make your sandwich.


And if the fridge has no milk and cheese and butter, then you must still go to the store and purchase the missing items before making a sandwich, regardless of whether you have bread or not (it's implied that you will also check the bread bin and if there is no bread you'll pick some up while you're getting the other things on your list, so you don't need to check again).

if Statements

You learned a little about the if statement in Chapter 2, and having touched upon it again here, you probably have a good idea of how it works. Abstractly it works like this:


if (a condition is true) { execute a line of code; }

The if statement only executes any code (within the curly braces) if the condition is true. If the condition isn't met, then the code is completely ignored, and isn't executed by PHP at all.
Here's another example:


if (weather is rainy) { put up umbrella; }
go outside;

The second line executes no matter what, but you only put up your umbrella if it is raining.
If you need to execute a whole section of code, you need to put the code on separate lines after the condition and between braces:


if (a condition is true){
   execute the contents of these braces;
}
So to expand on the umbrella example, you could say:
if (weather is rainy){
   put up umbrella;
   put on raincoat;
}
go outside;

Once again the "go outside" clause is always executed, but you only put up the umbrella and put on the raincoat if the condition "weather is rainy" is true.

Using Boolean Operators in Control-Flow Structures

Some of the most common (you may have noticed these already) uses for Boolean terms and values are in control-flow structures such as the if..then..else statement and switch..case statement. These structures depend upon evaluation of expressions that result in a Boolean value (true or false). If the result is true, one set of statements is run; if not, another set of statements is run.


Operators that result in a Boolean value are called Boolean operators, and include comparison operators (such as greater-than and less-than), equals and not equals, and so on. Some of these were introduced in Chapter 3 so that you could make a decision in the loan application form. In fact, any time you need to create a condition to make any kind of decision, you have to use one of these operators. There are four broad categories, and you should examine examples of each one in action.

The > and < Operators

You're probably already familiar with the greater than and less than operators—they're fairly fundamental in basic math and are equally important in programming. In PHP you can use them to compare two constants, a constant with a variable, or two variables. Depending on what the outcome of the comparison is, a certain course of action can be pursued. With constants, the result is self-evident, as this example shows:


if (5 < 6) { echo "Five is smaller than six"; }

You still need to dig below the surface to examine what's going on. The conditional part of the if statement is the part contained within parentheses. It can evaluate to one of the two Boolean values, true or false. In fact, that's all it can ever evaluate to because either a condition is met or it isn't met. So the example line returns true. The if statement only executes if the condition inside evaluates to true.


The preceding example isn't all that useful because you already know that five is smaller than six. However, if you compare the contents of a variable to a number, such as a lucky number, then the answer depends upon the value of the variable $lucky_number:


If ($lucky_number < 6) { echo "Our lucky number is smaller than six"; }

Or, you can compare two variables for an outcome:


If ($lucky_number < $lottery_number) { echo "Our lucky number is too small"; }

And of course, you can use the results of this condition to not just display a message but to determine a particular course of action:


If ($lucky_number < $lottery_number){
   echo "Our lucky number is too small";
    $lucky_number = $lucky_number + 1;
}

Here's a simple example in which the PHP program "thinks" of a number between one and ten and you have to guess the number. To get PHP to "think" of a number, you use the PHP random number generating function named rand(). How it works is discussed after the example.


Try it Out: Use Comparison Operators
Start example
  1. Open up your Web page editor and type in the following:
    <html>
    <head><title></title></head>
    <body>
    <?php
    if (isset($_POST['posted'])) {
       $number = rand(1,10);
       if ($_POST['guess'] > $number) {
          echo "<h3>Your guess is
           too high</h3>";
          echo "<br>The number is
           $number, you don't win, please play again<hr>";
       } else if ($_POST['guess'] < $number) {
          echo "<h3>Your guess is too low</h3>";
          echo "<br>The number is
           $number, you don't win, please play again<hr>";
       } else {
          echo "<br>The number is
           $number, you win, please play again<hr>";
       }
    }
    ?>
    <form method="POST" action="guessgame.php">
    <input type="hidden" name="posted" value="true">
    What number between 1 and 10 am I thinking of?
    <input name="guess" type="text">
    <br>
    <br>
    <input type="submit" value="Submit''>
    </form>
    </body>
    </html>
    
  2. Save the file as guessgame.php, and open it in your browser. Enter a guess in the text field and click the Submit button.
End example
How it Works
This example cheats a little bit in that it doesn't get PHP to generate a random number until after the user submits his guess. This has no effect on the outcome, because the random number generated is totally uninfluenced by the guess the user has supplied. Here's the code that creates the random number:


$number = rand(1,10);

The rand() function is extremely simple to use—you just supply it with a minimum value and a maximum value separated by a comma and it generates a random number between and including these two values. The result is stored in the $number variable.


When it first opens, the form asks the user for a number and stores the answer in a text box with the name attribute set to guess.


What number between 1 and 10 am I thinking of?

<input name="guess" type="text">

The data in the guess input field is passed back to script when the form is submitted; the $_POST[posted] variable is set, so you can use the isset() function to tell whether to perform the rest of the processing (the first if statement).


Then comparison operators are used to determine if the number submitted is higher, lower, or the same as the random number chosen. The number that the user supplied, which is stored in $_POST[guess], is compared to the number that PHP is "thinking" of. If the value stored in $guess is higher than the value stored in $Number, the code between the next set of braces is executed:


if ($_POST['guess'] > $number) {
      echo "<h3>Your guess is
       too high</h3>";
      echo "<br>The number is
       $number, you don't win, please play again<hr>";

The code after the first curly brace informs the user that the guess was too high, tells him what the number the program was "thinking" of, and invites him to play again.


Next, there is an else if statement. To get it started, end the first block of code with a closing curly brace, write in the else if statement, and begin another code block with an opening curly brace. This statement acts as another if statement, and checks to see if the guess is too low. If so, the code in its block is executed:


} else if ($_POST['guess'] < $number) {
      echo "<h3>Your guess is too low</h3>";
      echo "<br>The number is
       $number, you don't win, please play again<hr>";

This time the user is informed that his guess was too low, told what the number was, and invited to play again.


The final code block completes the PHP script. If the script gets this far, the user's number is already determined to be neither too high nor too low and must match the program's random number, so the else block of code executes. It tells the user that he's won and asks him to play again:


} else {
      echo "<br>The number is
       $number, you win, please play again<hr>";
   }
}
?>

The main effect of using the hidden form field and the isset() function is to cause the programming to run only if the form has been submitted.

The == and === Operators

You might already have noted that the equals sign has two different distinct usages in PHP. The single equal sign is the assignment operator; the double equal sign is the equality operator. This is an important difference, if you consider the following:


$lucky_number = 5;
$lucky_number = 7;

These lines set the value of $lucky_number as 5 and then, whatever was previously the value (5, in this case) in the variable is assigned a new value (7). In other words, the second line here overrides the first line.


What's different is that the equality operator doesn't affect the contents of the variable in any way in the following line:


if ($lucky_number == 7) echo ("Your lucky number is seven");

Other programming languages, such as Visual Basic, use the equals sign (=) not strictly as an assignment operator, but also as a comparison operator, depending upon context. It's very easy to make the mistake of assigning a value when you mean to compare values in PHP, if you are used to the way other languages do comparisons. For example:
$lucky_number = 5;

If ($lucky_number = 7) {
   echo "Your number is $lucky_number";
} else {
   echo "Your number is $lucky_number";
}

In this example, the output will be "Your number is 7" (the first case), rather than "Your number is 5" (the second case), because rather than comparing the two values, the equals sign within the if statement actually resets the value (assigns the value) of 7 to $lucky_number. Remember, in PHP you must be sure that you use single for assignment and double for equality. If you don't you might get unexpected results.


There is a second version of the equality operator, one that was introduced in PHP4.01. This operator uses three equals signs and evaluates to true only if the values are equal and the data types of the values/variables are also equal:


if ($lucky_number === $random_number) {
   echo "Your lucky number is $random_number";
}

The triple equals sign is very useful in situations where you need to know not just whether the values are equal, but are also the exact same type, such as when you want to know if you have a Boolean true or false value, and not a value that resolves to one of them without actually being a Boolean type (as discussed in the "Boolean Values" section earlier in the chapter).

The != and <> Operators

The reverse of the equality operator == is the inequality operator ! =. If you happen to be reading someone else's PHP code, it's easy to miss the ! sign (exclamation point), but it makes a world of difference to the meaning of the expression, so keep your eyes peeled for it.


if ($lucky_number != 7) {
   echo ("Your lucky number most definitely isn't seven");
}

The symbols ! = literally stand for not equal to!


There is a second notation for not equal to, using the less than and greater than operators. It's used in the following way in an if statement:


if ($lucky_number <> 7) {
   echo ("Your lucky number most definitely isn't seven");
}

The only time that either of these operators (! = or <>) causes the expression to evaluate to false is if the value in $lucky_number is 7. Just think of the <> operator as "not."
Let's reuse the simple question/radio-button answer script from Chapter 3. This time you'll not only ask the question, but also tell the user whether he got the answer correct.


Try it Out: Use the Equality and Inequality Operators
Start example
  1. Open your Web page editor, and type in all of the following code:
    <html>
    <head><title></title></head>
    <body>
    <?php
    if (isset ($_POST['posted'])) {
       if ($_POST['question1'] == "Lisbon") {
          echo "You are correct, $_POST[question1] is the right answer<hr>";
       }
    
       if ($_POST['question1') != "Lisbon") {
          echo "You are incorrect, $_-POST[question1] is not. the right answer<hr>";
       }
    }
    ?>
    <form method="POST" action="quiz.php">
    <input type="hidden" name="posted" value="true">
    What is the capital of Portugal?
    <br>
    <br>
    <input name=''question1" type=''radio" value=''Porto''>
    Porto
    <br>
    <input name=''question1" type="radio" value=''Lisbon''>
    Lisbon
    <br>
    <input name="question1" type="radio" value=''Madrid''>
    Madrid
    <br>
    <br>
    <input type=''submit''>
    </form>
    </body>
    </html>
    
  2. Save the as quiz.php, and close it.
  3. Open the file in your browser, choose Madrid as the answer, and click Submit Query. Figure 4-2 shows the result.
  4. Try a different answer by selecting a different city on this screen, to see what the response is.
End example
How it Works
The if statements simply check for the value Lisbon attached to the variable named $_POST[question1]. If the value is Lisbon, you give a positive response; if the value is not Lisbon, you provide a negative response.

Logical Operators (AND, OR,!)

The logical operators are a little less fearsome than they sound, and although they were discussed earlier in the Boolean sections of the chapter, it's time for you to put them to work. One good way to understand how to incorporate them into your programs to simply say what they do in plain language, because their English usage alerts you to the way they are used in PHP. For example, if the day is Sunday and the weather is sunny, then you will go to the beach. The same goes for PHP:


if ($day == "Sunday" AND $weather === "Sunshine") {
   echo ("Off to the beach then");
}
AND can also be written using the ampersand operator twice (&&):
if ($day == "Sunday" && $weather == "Sunshine") {
   echo ("Off to the beach then");
}

The OR and ! operators are similarly straightforward. You could rephrase the example code by using the OR operator to say the opposite thing:


if ($day == "Monday" OR $weather == "rainy") {
   echo ("Not going to the beach today then");
}

If it is Monday or the weather is raining then you can't got to the beach. The OR operator is also represented by the double bar (double pipe) sign ||, so the preceding code can also be written like this:


if ($day == "Monday" ||$weather == "rainy") {
   echo ("Not going to the beach today then");
}

An interesting note that probably won't affect your code, but one that you should be aware of, is that the && and AND operators have slightly different precedence. The same goes for the || and OR operators. The && and || operators take precedence over their textual alternatives.
Although there is a NOT operator, you can't use the word "not." The NOT operator is actually an exclamation mark. If it goes outside the parentheses, it reverses the result inside them, so that if the condition is originally returns true, then it becomes false, and vice versa. For example, if the day isn't Sunday then you can't go to the beach:


if !($day == "Sunday") {
   echo ("Not going to the beach today then");
}

You might surmise that this has exactly the same effect as the inequality operator ! = introduced earlier, but it doesn't. The inequality operator applies only to the expression it is part of, although the exclamation point outside of the parentheses in an if statement applies to the entire condition (the part inside the parentheses). In fact, you can reverse the result of a condition that doesn't even have any operators in it. Just place a variable inside a condition part of an if statement, and if the variable has no value, the following code shows how the condition will then be false, but will be activated if the condition is preceded by the exclamation point. If you read it to yourself, it sounds like, "If the $answer variable does not contain anything, then echo a statement."


if !($answer) {
   echo ("There's no answer");
}

This statement only prints a message if there is no value in the $answer variable or the value is zero (which in PHP is equivalent to being empty). Can you work out why? It's because the ! operator negates the truth-value of $answer, so if $answer returns false, !($answer) returns true, and the if statement executes. This is an important point because oftentimes the condition you'll use in an if statement is simply the result of evaluating an expression or the result of a function, and if true, the if statement proceeds with processing, and if false, it does not. There may be no operators whatsoever in the condition.


There's still quite a bit more detail to go into about logical operators, but to break it up, try out this little program that uses a couple of these operators.


Try it Out: Use the Logical Operators
Start example
Here's a program that a car hire company might use to verify whether somebody can drive one of its cars. A prospective driver must hold a driving license, and be aged 21 or older. This program checks for these details and more.
  1. Open your Web page editor and type in the following code:
    <html>
    <head><title></title></head>
    <body>
    <b>Namllu car hire company</b>
    <?php
    if (isset($_POST['posted'])) {
       if ($_POST['age'] > 20 and $_POST['license'] == "on") {
          echo ("Your car hire has been accepted.<hr>");
       }
    
       if ($_POST['age'] < 21 or $_POST['license'] =="") {
          echo ("Unfortunately we cannot hire a car to you.<hr>");
       }
    } else {
    ?>
    <form method="post" action="car.php">
    <input type="hidden" name="posted" value="true">
    First name:
    <input name ="first_name" type ="text">
    Last name:
    <input name ="Last_name" type ="text">
    age:
    <input name ="age" type="text"size"3">
    <br>
    <br>
    Address:
    <textarea name= "address" rows = 4 cols=40>
    </textarea>
    <br>
    <br>
    Do you hold a current driving license?
    <input name="license" type="checkbox">
    <br>
    <br>
    <input name="license" type=" checkbox">
    <input type="submit" value="Submit application">
    </form>
    </body>
    </html>
    <?php
    }
    ?>
    
  2. Save this file as car.php and close it.
  3. Open the file in your browser and type in some details.
  4. Click Submit application.
End example
How it Works
To pick up additional information, this HTML form is a bit longer than other forms you've made (the artists among you may want to lay out the form better, but simple works best for now). There's also an else statement to cause the form to be displayed only if it has not been posted, because once a person has an acceptable application there's no need to redisplay the form (don't forget to put the <?}?> after the end of the HTML form).


Proper processing of the PHP code depends on picking up data from two HTML input fields (a text box named age and a check box named license). These variables are received as $_POST[age] and $_POST[license] after the form's submitted. The following HTML does the work of providing the form and Submit button.


<input name="age" type="text"size="3">
<br>
<br>
Address:
<textarea name="address" rows=4 cols=40>
</textarea>
<br>
<br>
Do you hold a current driving license?
<input name="license" type="checkbox">

The text box has the name attribute age, so a variable named $_POST[age] is created to hold the user's age. The check box control (license) is either set to on or off. The $_POST[license] variable can either hold the value on or it can hold no value at all.
The value on is actually browser dependent, but given that Internet Explorer, Netscape Navigator, and Opera all use it, you shouldn't encounter any problems using it. If your browser is different and the example doesn't work, then use the echo() statement to interrogate the $license variable, and amend the code accordingly (more about using the echo() statement for debugging purposes in Chapter 5).
The PHP script makes use of both these variables. The first if statement in car.php says that if the age is greater than 20, and the user is a license holder, then you can accept the car hire:


if ($_POST['age'] > 20 and $_POST['license'] == "on") {
      echo ("Your car hire has been accepted.<hr>");
}

The second block says the reverse: if either the user's age is less than 21, or the user isn't a license holder, the car rental is refused:


if ($ POST['age'] < 21 or $ POST['license'] == "") {
      echo ("Unfortunately we cannot hire a car to you.<hr>");
 }

That's all there is to the script.


One last contingency: what happens if the user puts in an age between 20 and 21, say 20.5? Unlikely, but something the script should be able to handle. The script actually pushes the boundaries a little, because either age condition will accept it and you will get two answers. In situations like this, perhaps it would be best to use the >= or <= operators (greater-than or equal-to and less-than or equal-to). Makes sense, doesn't it? You could use the following code to produce a better result:


if ($_POST['age'] >= 21 and $_POST['license'] == "on") {
      echo ("Your car hire has been accepted.<hr>");
} else {
      echo ("Unfortunately we cannot hire a car to you.<hr>");
}

switch Statements

In using the if statement, you've probably noticed that sometimes there are multiple conditions to check for. You could write large if statements with else if blocks, but frequently it's just easier to write a switch statement. The switch statement works exactly like it sounds; it switches control from one block to another based on a particular input value.


Here's an example of the switch statement in use:


switch ($grade) {
   case $grade>90:
        echo ("You got an A.");
        break;
   case $grade>80:
      echo ("You got a B.");
      break;
   case $grade>70:
      echo ("You got a C.");
      break;
   case $grade>50:
      echo ("You got a D.");
      break;
   case $grade<50:
      echo ("You got an F. ");
      break;
   default:
      echo ("You failed");
}

Instead of if and else if, there's now just case (represented by the variable named $grade), followed by code blocks that each test for the value of $grade, and then a set of actions. In each case the PHP program has something different to execute. It's good practice to have a default case because default is a catch-all that makes sure something happens (leave default out, and you'll realize it when all you get is a blank screen with no output and also no error messages).


You will have noticed the break command in the switch statement. When PHP encounters break, it stops what it's doing, drops out of the whole switch structure, and picks up the programming thread after the closing brace. It doesn't continue checking for further compliance with other criteria, even though a grade of 80 percent would have met all of these criteria. This is useful because you don't have to write countless little catch-alls for every conceivable situation. If you want all criteria checked, then just omit the keyword break, although you should note that break only works in conjunction with the switch statement, and not the if statement (but note that you can confuse yourself if you put a break within an if statement that happens to be inside a switch statement or for loop, and so on, because although the if statement won't break, the switch statement or for loop will).


If you omit the word break, all statements evaluate to true, and you get A, B, C, D, and F with a score of 80.


switch ($State) {
   case "IL":
        echo ("Illinois");
        break;
   case "GA":
        echo ("Georgia");
        break;
   default:
        echo ("California");
        break;
}

If you just supply a value (IL, in this example) next to the case keyword, PHP automatically checks the variable you supplied in the switch parentheses for equality with the value next to case, whether numerical or textual.
There's a colon, not a semicolon, after the case keyword. Actually, either colon or semicolon works fine (the colon is used in the online documentation), so use whichever you please.
You should only provide cases for values you expect to occur and intend to work with (even if you simply want the switch statement to break off processing). For example, you can leave case occurrences within switch empty except for a break statement. Then, if that case is encountered, the switch statement will break and no more processing within it will occur. That happens in the following code if someone enters HH for the $State variable. The case for HH is activated and processing ends, unlike what happens for values that are unknown, which activates the default case and echoes out California):


switch ($State) {
   case "HH":
     break;
   case "IL":
      echo ("Illinois");
      break;
   case "GA":
      echo ("Georgia");
      break;
   default:
      echo ("California");
      break;
   }

Try it Out: Use switch Statements
Start example
This example creates a form that enables the user to select destination and grade values for booking a holiday. These values are then used to (very simply) calculate a price for the type of vacation selected.
  1. Open your text editor and type in the following:
    <html>
    <head><title></title></head>
    <body>
    <b>Namllu holiday booking form</b>
    <br>
    <br>
    <?php
    if (isset($_POST['posted'])) {
       $price = 500;
         $starmodifier = 1;
       $citymodifier = 1;
       $destination = $_POST['destination'];
       $destgrade = $_POST['destination'] . $_POST['grade'];
         switch($destgrade) {
          case "Barcelonathree":
             $citymodifier = 2;
             $price = $price * $citymodifier;
             echo "The cost for a week in $destination is $price";
             break;
          case "Barcelonafour":
             $citymodifier = 2;
             $starmodifier = 2;
             $price = $price * $citymodifier * $starmodifier;
             echo "The cost for a week in $destination is $price";
             break;
          case "Viennathree":
          Scitymodifier = 3.5;
             $price = $price * $citymodifier;
             echo "The cost for a week in $destination is $price";
             break;
          case "Viennafour":
             $citymodifier = 3.5;
             $starmodifier = 2;
             $price = $price * $citymodifier * $starmodifier;
             echo "The cost for a week in $destination is $price";
             break;
          case "Praguethree":
             $price = $price * $citymodifier;
             echo "The cost for a week in $destination is $price";
             break;
          case "Praguefour":
             $Price = $Price * $citymodifier;
             echo "The cost for a week in $destination is $price";
             break;
          default:
             echo ("Go back and do it again");
             break;
       }
    }
    ?>
    <form method="POST" action="holiday.php">
    <input type="hidden" name="posted" value="true">
    Where do you want to go on holiday?
    <br>
    <br>
    <input name="destination" type="radio" value=''Prague">
    Prague
    <br>
    <input name="destination" type="radio" value="Barcelona">
    Barcelona
    <br>
    <input name="destination" type="radio" value="Vienna">
    Vienna
    <br>
    <br>
    What grade of hotel do you want. to stay at?
    <br>
    <br>
    <input name="grade" type="radio" value="three">
    Three star
    <br>
    <input name="grade" type="radio" value="four">
    Four star
    <br>
    <br>
    <input type="submit" value="Book Now">
    </form>
    </body>
    </html>
    
    
  2. Save the file as holiday.php and close it.
  3. Now open the file in your browser, enter some details in the form, and click the Book Now button.
End example
How it Works
There were two claims about switch: that it's easier to read and that it uses few lines of code. The first is subjective. Consider the second: this program could have been written as a series of if statements, and it would have used a huge number lines of PHP script in between the <?php?> markers, as you can imagine, but holiday.php has used just 41 lines.


Take a look at how this comes together. When the page is opened, you see the HTML form and understand that you need to make some choices. Once the form is submitted, the PHP code is activated because the $_POST[posted] variable is set, and this is detected within the first (and only) if statement by the isset() function. Next, the code inside the if statement begins to run, starting by setting a few variables, as shown here:


   $price = 500;
   $starmodifier = 1;
   $citymodifier = 1;

$destination = $_POST['destination'];

The next line introduces a new variable, $destgrade, which is a concatenation of the contents of the $_POST['destination'] and $_POST['grade'] variables.


$destgrade = $_POST['destination'] . $_POST['grade'];

So, if you chose Barcelona and four star, $destgrade would contain Barcelonafour. The number of lines is reduced (over multiple if statements) in part by feeding the condition variable to the switch statement only once:


switch($destgrade) {

All seven possible outcomes need to be captured. (The three hotel choices multiplied by two star grades is six, plus anything that isn't one of these choices.) The six possible correct outcomes are Barcelona and three star, Barcelona and four star, Prague and three star, Prague and four star, Vienna and three star, Vienna and four star. So the possible variables in $destgrade can only be Barcelonathree, Barcelonafour, Praguethree, Praguefour, Viennathree, and Viennafour, and a case is tailor-made for each.


Because all of the cases perform a similar action, just examine this one example:


case "Barcelonathree":
   $citymodifier = 2;
   $price = $price * $citymodifier;
   echo "The cost for a week in $destination is $price";
   break;

For the Barcelonathree case, the $citymodifier is set to two and multiplied by the price. Then the price and destination are displayed and you break to the end of the program. If the value in $destgrade doesn't match any correct case, then something must be wrong and you tell the user to go back and do it again.


It's good practice to add a break at the end even though it does nothing:


   default:
      echo ("Go back and do it again");
      break;
}

It means that your code is less likely to generate errors if you ever add another case after the else.