Using Else

I l @ ve RuBoard

The next logical formation after an if conditional is the if-else (sometimes called the if-then-else ) conditional. This allows you to establish a condition as to why one statement would be executed and then another statement which would be executed if that condition is not met.

 if (condition) {     statement(s); }  else {     statement(s)2; } 

The important thing to remember when using this construct is that unless the condition is explicitly met, the else statement will be executed. In other words, the statements after the else constitute the default action while the statements after the if condition are the exception to the rule. You can now rewrite the numbers .php page incorporating else into the if statement.

To use else:

  1. Open numbers.php in your text editor (Script 6.4).

  2. Immediately after the closing curly brace of your if conditional (line 30), type (Script 6.5):

     else {  print ("Please make sure that   you have entered both a quantity   and an applicable discount and   then resubmit.\n"); } 
    Script 6.5. You'll normally find that it makes sense to write if-else conditionals instead of just standard if conditionals (as you've done here) since you'll likely want to perform some action if a condition you were expecting isn't met.

    graphics/06sc05.jpg

    Rather than just display a blank screen if the page does not receive a quantity, it will now print an appropriate error message.

  3. Save your script, upload it to your server, and test in your Web browser (Figure 6.7).

    Figure 6.7. Now you've achieved a far more professional Web site that reacts according to what the user or system doesin this case, omitting the quantity. Conditionals help you prepare against assumptions which may or may not come true.

    graphics/06fig07.gif

Tip

You could also, at this time, add an if-else conditional to numbers.php so that a message is printed if the discount does apply. Or, if you want to be very particular, you could use an if-else conditional to print the singular "widget" if only one widget is ordered but the plural "widgets" otherwise (as opposed to "widget(s)"as I've been writing).


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net