Conditionals and Operators


Conditionals, like variables, are integral to programming, and most people are familiar with them in some form or another. Dynamic Web pages, as you might imagine, frequently require the use of conditionals to alter a script's behavior according to set criteria.

PHP's three primary terms for creating conditionals are if, else, and elseif (which can also be written as two words, else if).

Every conditional includes an if clause:

 if (condition) {    // Do something! } 

This in turn can become

 if (condition) {    // Do something! } else {    // Do something else! } 

and

 if (condition1) {    // Do something! } elseif (condition2) {    // Do something else! } else {    // Do something different! } 

If a condition is true, the code in the following curly braces ({}) will be executed. If not, PHP will continue on. If there is a second condition (after an elseif), that will be checked for truth. The process will continueyou can use as many elseif clauses as you wantuntil PHP hits an else, which will be automatically executed at that point, or until the conditional terminates without an else.

For this reason, it's important that the else always come last and be treated as the default action unless specific criteria (the conditions) are met.

A condition can be true in PHP for any number of reasons. These are common true conditions:

  • $var, if $var has a value other than 0, an empty string, or NULL

  • isset($var), if $var has any value other than NULL, including 0 or an empty string

  • TRUE, true, true, etc.

In the second example, a new function, isset(), is introduced. This function checks if a variable is set, meaning that it has a value other than NULL. You can also use the comparative and logical operators (Table 2.1) in conjunction with parentheses to make more complicated expressions.

Table 2.1. These operators are frequently used when writing conditionals.

Comparative and Logical Operators

SYMBOL

MEANING

TYPE

EXAMPLE

==

is equal to

comparison

$x == $y

!=

is not equal to

comparison

$x != $y

<

less than

comparison

$x < $y

>

greater than

comparison

$x > $y

<=

less than or equal to

comparison

$x <= $y

>=

greater than or equal to

comparison

$x >= $y

!

not

logical

!$x

&&

and

logical

$x && $y

||

or

logical

$x || $y

XOR

and not

logical

$x XOR $y


To use conditionals

1.

Open handle_form.php (refer to Script 2.3) in your text editor.

2.

Before the echo() statement, add a conditional to create the $gender variable (Script 2.4).

 if (isset($_REQUEST['gender'])) {   $gender = $_REQUEST['gender']; } else {   $gender = NULL; } 

Script 2.4. Conditionals in your code allow you to modify behavior according to specific criteria.


This is a simple and effective way to validate a form input (particularly a radio button, check box, or select). If the user checks either gender radio button, then $_REQUEST['gender'] will have a value, meaning that the condition isset($_REQUEST['gender']) is true. In such a case, the shorthand version of this variable$genderis assigned the value of $_REQUEST['gender'], repeating the technique used with $name, $email, and $comments. If the condition is not true, then $gender is assigned the value of NULL, indicating that it has no value. Notice that NULL is not in quotes.

3.

After the echo() statement, add another conditional that prints a message based upon $gender's value.

 if ($gender == 'M') {   echo '<p><b>Good day,    Sir!</b></p>'; } elseif ($gender == 'F') {   echo '<p><b>Good day,    Madam!</b></p>'; } else {   echo '<p><b>You forgot to enter    your gender!</b></p>'; } 

This if-elseif-else conditional looks at the value of the $gender variable and prints a different message for each possibility. It's very important to remember that the double equals sign (==) means equals, whereas a single equals sign (=) assigns a value. The distinction is important because the condition $gender == 'M' may or may not be true, but $gender = 'M' will always be true.

4.

Save the file, upload to your Web server, and test in your Web browser (Figures 2.8, 2.9, and 2.10).

Figure 2.8. The gender-based conditional prints a different message for each choice in the form.


Figure 2.9. The same script will produce different results (compare with Figure 2.8) when the form values change.


Figure 2.10. If no gender was selected, a message is printed indicating to the user their oversight.


Tips

  • It's standard procedure and good programming form to format your conditionals in such a way that it's clear that certain code is a subset of a conditional. In this script I've indented code one tab stop (or four spaces) from the line that governs it.

  • You canand frequently willnest conditionals (place one inside another).

  • The first conditional in this script (the isset()) is a perfect example of how to use a default value. The assumption (the else) is that $gender has a NULL value unless the one condition is met: that $_REQUEST['gender'] is set.

  • The curly braces used to indicate the beginning and end of a conditional are not required if you are executing only one statement. I would recommend that you almost always use them, though, as a matter of clarity.

  • Because it's very easy to mistakenly type $gender = 'M' instead of $gender == 'M', some people advocate rewriting such a condition as 'M' == $gender, which will create error messages if mistakenly typed as 'M' = $gender.


Switch

PHP has another type of conditional, called the switch, best used in place of a long if-elseif-else conditional. The syntax of switch is

 switch ($variable) {   case 'value1':     // Do this.     break;   case 'value2':     // Do this instead.     break;   default:     // Do this then.     break; } 

The switch conditional compares the value of $variable to the different cases. When it finds a match, the following code is executed, up until the break. If no match is found, the default is executed, assuming it exists (it's optional).

Hence, the conditional from Script 2.4 could be rewritten as

 switch ($gender) {   case 'M':     echo '<p><b>Good day, Sir!</b></p>';     break;   case 'F':     echo '<p><b>Good day, Madam!</b></p>';     break;   default:     echo '<p><b>You forgot to enter your gender!</b></p>';     break; } 

The switch conditional is limited in its usage in that it can only check a variable's value for equality against certain cases; more complex conditions cannot be easily checked.




    PHP and MySQL for Dynamic Web Sites. Visual QuickPro Guide
    PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    ISBN: 0321336577
    EAN: 2147483647
    Year: 2005
    Pages: 166
    Authors: Larry Ullman

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