2.1. Setting Up Conditions

Conditions are expressions that PHP tests or evaluates to see whether they are true or false. Conditions are used in complex statements to determine whether a block of simple statements should be executed. To set up conditions, you compare values. Here are some questions you can ask to compare values for conditions:

  • Are two values equal? Is Sally's last name the same as Bobby's last name? Or, is Nick 15 years old? (Does Nick's age equal 15?)

  • Is one value larger or smaller than another? Is Nick younger than Bobby? Or, did Sally's house cost more than a million dollars?

  • Does a string match a pattern? Does Bobby's name begin with an S? Does the ZIP code have five numeric characters?

You can also set up conditions in which you ask two or more questions. For example, you may ask: Is Nick older than Bobby and is Nick younger than Sally? Or you may ask: Is today Sunday and is today sunny? Or you may ask: Is today Sunday or is today Monday?

2.1.1. Comparing values

You can compare numbers or strings to see whether they are equal, whether one is larger than the other, or whether they are not equal. You compare values with comparison operators. PHP evaluates the comparison and returns true or false. For example, the following is a simple comparison:

$result = $a == $b;

The comparison operator == checks whether two values are equal. If $a and $b are equal, $result is assigned the Boolean value true. If $a and $b are not equal, $result is assigned false. Thus, $a == $b is a simple condition that is either true or false.

PHP offers several comparison operators that you can use to compare values. Table 2-1 shows these comparison operators.

Table 2.1. Comparison Operators
OperatorWhat It Means
==Are the two values equal in value?
===Are the two values equal in both value and data type?
>Is the first value larger than the second value?
>=Is the first value larger than or equal to the second value?
<Is the first value smaller than the second value?
<=Is the first value smaller than or equal to the second value?
!=, <>Are the two values not equal to each other in value?
!==Are the two values not equal to each other in either value or data type?

You can compare both numbers and strings. Strings are compared alphabetically, with all uppercase characters coming before any lowercase characters. For example, SS comes before Sa. Punctuation characters also have an order, and one character can be found to be larger than another character. However, comparing a comma to a period doesn't have much practical value.

NOTE

Strings are compared based on their ASCII code. In the ASCII character set, each character is assigned an ASCII code that corresponds to a number between 0 and 127. When strings are compared, they are compared based on this code. For example, the number that represents the comma is 44. The period corresponds to 46. Therefore, if a period and a comma are compared, the period is evaluated as larger.

The following are some valid comparisons that PHP can test to determine whether they're true:

  • $a == $b

  • $age != 21

  • $ageNick < $ageBobby

  • $house_price >= 1000000

The comparison operator that asks whether two values are equal consists of two equal signs (==). One of the most common mistakes is to use a single equal sign for a comparison. A single equal sign puts the value into the variable. Thus, a statement like if ($weather = "raining") would set $weather to raining rather than check whether it already equaled raining, and would always be true.


If you write a negative (by using !), the negative condition is true. Look at the following comparison:

$age != 21

The condition being tested is that $age does not equal 21. Therefore, if $age equals 20, the comparison is true.

2.1.2. Checking variable content

Sometimes you just need to know whether a variable exists or what type of data is in the variable. Here are some common ways to test variables:

isset($varname)    # True if variable is set, even if
                     nothing is stored in it.
empty($varname)    # True if value is 0 or is a string with
                     no characters in it or is not set.

You can also test what type of data is in the variable. For example, to see whether the value is an integer, you can use the following:

is_int($number)

The comparison is true if the value in $number is an integer. Some other tests provided by PHP are as follows:

  • is_array($var2): Checks to see whether $var2 is an array

  • is_float($number): Checks to see whether $number is a floating point number

  • is_null($var1): Checks to see whether $var1 is equal to 0

  • is_numeric($string): Checks to see whether $string is a numeric string

  • is_string($string): Checks to see whether $string is a string

You can test for a negative, as well, by using an exclamation point (!) in front of the expression. For example, the following statement returns true if the variable doesn't exist at all:

!isset($varname)

2.1.3. Pattern matching with regular expressions

Sometimes you need to compare character strings to see whether they fit certain characteristics, rather than to see whether they match exact values. For example, you might want to identify strings that begin with S or strings that have numbers in them. For this type of comparison, you compare the string to a pattern. These patterns are called regular expressions.

You've probably used some form of pattern matching in the past. When you use an asterisk (*) as a wild card when searching for files (dir ex*.doc, for example), you're pattern matching. For example, ex*.txt is a pattern. Any string that begins with ex and ends with .txt, with any characters in between the ex and the .txt, matches the pattern. The strings exam.txt, ex33.txt, and ex3x4.txt all match the pattern. Using regular expressions is just a more powerful variation of using wild cards.

One common use for pattern matching is to check the input from a Web page form. If the information input doesn't match a specific pattern, it might not be something you want to store in your database. For example, if the user types a ZIP code into your form, you know the format needs to be five numbers or a ZIP + 4. So, you can check the input to see whether it fits the pattern. If it doesn't, you know it's not a valid ZIP code, and you can ask the user to type in the correct information.

Regular expressions are used for pattern matching in many situations. Many Linux commands, such as grep, vi, or sed, use regular expressions. Many applications, such as text editors and word processors, allow searches using regular expressions.

PHP provides support for Perl-compatible regular expressions. The following sections describe some basic Perl-compatible regular expressions, but much more complex and powerful pattern matching is possible. See www.php.net/manual/en/reference.pcre.pattern.syntax.php for further explanation of Perl-compatible regular expressions.

2.1.3.1. Using special characters in patterns

Patterns consist of literal characters and special characters. Literal characters are normal characters, with no special meaning. An e is an e, for example, with no meaning other than that it's one of 26 letters in the alphabet. Special characters, on the other hand, have special meaning in the pattern, such as the asterisk (*) when used as a wild card. Table 1-2 shows the special characters that you can use in patterns.

Table 2.2. Special Characters Used in Patterns
CharacterMeaningExampleMatchNot a Match
^Beginning of line.^ccatmy cat
$End of line.c$ticstick
.Any single character...Any string that contains at least two charactersa, I
?The preceding character is optional.mea?nmean, menmoan
( )Groups literal characters into a string that must be matched exactly.m(ea)nmeanmen, mn
[ ]Encloses a set of optional literal characters.m[ea]nmen, manmean, mn
-Represents all the characters between two characters.m[a-c]nman, mbn, mcnmdn, mun, maan
+One or more of the preceding items.door[1-3]+door111, door131door, door55
*Zero or more of the preceding items.door[1-3]*door, door311door4, door445
{,}The starting and ending numbers of a range of repetitions.a{2,5}aa, aaaaaa, xx3
The following character is literal.m*nm*nmen, mean
( | | )A set of alternative strings.(Tom|Tommy)Tom, TommyThomas, To

2.1.3.2. Considering some example patterns

Literal and special characters are combined to make patterns, sometimes long, complicated patterns. A string is compared with the pattern, and if it matches, the comparison is true. Some example patterns follow, with a breakdown of the pattern and some sample matching and non-matching strings.

2.1.3.2.1. Example 1
^[A-Za-z].*

This pattern defines strings that begin with a letter and have two parts:

  • ^[A-Za-z] The first part of the pattern dictates that the beginning of the string must be a letter (either upper- or lowercase).

  • .* The second part of the pattern tells PHP the string of characters can be one or more characters long.

The expression ^[A-Za-z].* matches the following strings: play it again, Sam and I.

The expression ^[A-Za-z].* does not match the following strings: 123 and ?.

2.1.3.2.2. Example 2
Dear (Kim|Rikki)

This pattern defines two alternate strings and has two parts:

  • Dear The first part of the pattern is just literal characters.

  • (Kim|Rikki) The second part defines either Kim or Rikki as matching strings.

The expression Dear (Kim|Rikki) matches the following strings: Dear Kim and My Dear Rikki.

The expression Dear (Kim|Rikki) does not match the following strings: Dear Bobby and Kim.

2.1.3.2.3. Example 3
^[0-9]{5}(-[0-9]{4})?$

This pattern defines any ZIP code and has several parts:

  • ^[0-9]{5} The first part of the pattern describes any string of five numbers.

  • - The slash indicates that the hyphen is a literal.

  • [0-9]{4} This part of the pattern tells PHP that the next characters should be a string of numbers consisting of four characters.

  • ( )? These characters group the last two parts of the pattern and make them optional.

  • $ The dollar sign dictates that this string should end (no characters are allowed after the pattern).

The expression ^[0-9]{5}(-[0-9]{4})?$ matches the following strings: 90001 and 90002-4323.

The expression ^[0-9]{5}(-[0-9]{4})?$ does not match the following strings: 9001 and 12-4321.

2.1.3.2.4. Example 4
^.+@.+.com$

This pattern defines any string with @ embedded that ends in .com. In other words, it defines a common format for an e-mail address. This expression has several parts:

  • ^.+ The first part of the pattern describes any string of one or more characters that precedes the @.

  • @ This is a literal @ (at sign). @ is not a special character and does not need to be preceded by .

  • .+ This is any string of one or more characters.

  • . The slash indicates that PHP should look for a literal dot.

  • com$ This defines the literal string com at the end of the string, and the $ marks the end of the string.

The expression ^.+@.+.com$ matches the following strings: [email protected] and [email protected].

The expression ^.+@.+.com$ does not match the following strings: [email protected], [email protected], and @you.com.

2.1.3.3. Using PHP functions for pattern matching

You can compare whether a pattern matches a string with the preg_match function. The general format is as follows:

preg_match("pattern",value);

The pattern must be enclosed in a pair of delimiters — characters that enclose the pattern. Often, the forward slash (/) is used as a delimiter. However, you can use any nonalphanumeric character, except the backslash (). For example, to check the name that a user typed in a form, match the pattern with the name (stored in the variable $name), as follows:

preg_match("/^[A-Za-z' -]+$/",$name)

The pattern in this statement does the following:

  • Encloses the pattern in forward slashes (/).

  • Uses ^ and $ to signify the beginning and end of the string, respectively. That means that all the characters in the string must match the pattern.

  • Encloses all the literal characters that are allowed in the string in [ ]. No other characters are allowed. The allowed characters are upper- and lowercase letters, an apostrophe ('), a blank space, and a hyphen (-).

    You can specify a range of characters by using a hyphen within the [ ]. When you do that, as in A-Z, the hyphen doesn't represent a literal character. Because you also want a hyphen included as a literal character that is allowed in your string, you need to add a hyphen that isn't between any two other characters. In this case, the hyphen is included at the end of the list of literal characters.

  • Follows the list of literal characters in the [ ] with a +. The plus sign means that the string can contain any number of the characters inside the [ ], but must contain at least one character.

If the pattern itself contains forward slashes, the delimiter can't be a forward slash. You must use another character for the delimiter, such as:

preg_match("#^[A-Za-z' -/]+$#",$name)

2.1.4. Joining multiple comparisons

Often you need to ask more than one question to determine your condition. For example, suppose your company offers catalogs for different products in different languages. You need to know which type of product catalog the customer wants to see and which language he or she needs to see it in. This requires you to join comparisons, which have the following the general format:

comparison1 and|or|xor comparison2 and|or|xor comparison3 and|or|xor ...

Comparisons are connected by one of the following three words:

  • and: Both comparisons are true.

  • or: One of the comparisons or both of the comparisons are true.

  • xor: One of the comparisons is true but not both of the comparisons.

Table 2-3 shows some examples of multiple comparisons.

Table 2.3. Multiple Comparisons
ConditionIs True If . . .
$ageBobby == 21 or $ageBobby == 22Bobby is 21 or 22 years of age.
$ageSally > 29 and $state =="OR"Sally is older than 29 and lives in Oregon.
$ageSally > 29 or $state == "OR"Sally is older than 29 or lives in Oregon or both.
$city == "Reno" xor $state == "OR"The city is Reno or the state is Oregon, but not both.
$name != "Sam" and $age < 13The name is anything except Sam and age is under 13 years of age.

You can string together as many comparisons as necessary. The comparisons using and are tested first, the comparisons using xor are tested next, and the comparisons using or are tested last. For example, the following condition includes three comparisons:

$resCity == "Reno" or $resState == "NV" and $name == "Sally"

If the customer's name is Sally and she lives in NV, this statement is true. The statement is also true if she lives in Reno, regardless of what her name is. This condition is not true if she lives in NV but her name is not Sally. You get these results because the script checks the condition in the following order:

  1. The and is compared.

    The script checks $resState to see whether it equals NV and checks $name to see whether it equals Sally. If both match, the condition is true, and the script doesn't need to check or. If only one or neither of the variables equal the designated value, the testing continues.

  2. The or is compared.

    The script checks $resCity to see whether it equals Reno. If it does, the condition is true. If it doesn't, the condition is false.

You can change the order in which comparisons are made by using parentheses. The connecting word inside the parentheses is evaluated first. For example, you can rewrite the previous statement with parentheses as follows:

($resCity == "Reno or $resState == "NV") and $name == "Sally"

The parentheses change the order in which the conditions are checked. Now the or is checked first because it's inside the parentheses. This condition statement is true if the customer's name is Sally and she lives in either Reno or NV. You get these results because the script checks the condition as follows:

  1. The or is compared.

    The script checks to see whether $resCity equals Reno or $resState equals NV. If it doesn't, the entire condition is false, and testing stops. If it does, this part of the condition is true. However, the comparison on the other side of the and must also be true, so the testing continues.

  2. The and is compared.

    The script checks $name to see whether it equals Sally. If it does, the condition is true. If it doesn't, the condition is false.

Use parentheses liberally, even when you believe you know the order of the comparisons. Unnecessary parentheses can't hurt, but comparisons that have unexpected results can.


NOTE

If you're familiar with other languages, such as C, you might have used || (for or) and && (for and) in place of the words. The || and && work in PHP as well. The statement $a < $b && $c > $b is just as valid as the statement $a < $b and $c > $b. The || is checked before or, and the && is checked before and.

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

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