I l @ ve RuBoard |
Logical operators help you create reasonable constructsstatements that have a value of either TRUE or FALSE. In PHP, a condition is TRUE if it is simply a variable name and that variable has a value that is not zero (as you've seen already), such as: $Variable = 5; if ($Variable) { ... A condition is also TRUE if it makes logical sense, like: if (5 >= 3) { ... Your condition will be FALSE if it refers to a variable and that variable has no value or if you have created an illogical construct. The following conditional will always be false: if (5 <= 3) { ... To go beyond simple one-part conditions, PHP supports six types of logical operators: two versions of and (AND or &&); two versions of or (OR or a character called the pipe put together twice); not (NOT); and or not (XOR). When you have two options for one operator (as with and and or ), they differ only in precedence. See Appendix C, PHP Resources, to view the table of operator precedence. Using parentheses and logical operators, you can create even more in-depth conditionals for your if conditionals. For an AND conditional, every conjoined part must be TRUE. With OR, one subsection must be TRUE to render the whole condition TRUE. These conditionals are TRUE: if ( (5 <= 3) OR (5 >= 3) ) { ... if ( (5 > 3) AND (5 < 10) ) { ... These conditionals are FALSE: if ( (5 != 5) AND (5 > 3) ) { ... if ( (5 != 5) OR (5 < 3) ) { ... As you construct your conditionals, remember two important things: first, in order for the statements which are the result of a conditional to be executed, the conditional has to have a TRUE value; second, by using parentheses, you can ignore rules of precedence and insure that your operators are addressed in the order of your choosing. To demonstrate logical operators, you should add another conditional to the numbers .php page letting the user know if their discount does not apply. To use logical operators:
Tip It is another common programming conventionwhich I've maintained in this bookto write the terms TRUE and FALSE in all capitals. Tip It is very easy in long, complicated conditionals to forget an opening or closing parentheses, which will either produce error messages or unexpected results. Find some system (like spacing out your conditionals as I have done) to help clarify your code. |
I l @ ve RuBoard |