IfThen Statements

   

If/Then Statements

One of the most common PHP language constructs that you will encounter is the if/then statement. The if/then statement allows you to evaluate an expression and then, depending if it is true or not, take a course of action. For example:

 $a = 1;  if($a) {       echo "True!"; } 

Since $a = 1, then PHP interprets it in the context of the if statement to be a boolean type. Since 1 = true, the if statements prints out the message. Literally you can read it as "If True, then print out "True!".

Another example, but this time with an "else" clause:

 $a = 5;  $b = "10"; if($a > $b) {     echo "$a is greater than $b"; } else {     echo "$a is not greater than $b"; } 

PHP doesn't care that $a is an integer and $b is a string. It recognizes that $b also makes a pretty good integer as well. It then evaluates the expression, "If $a is greater than $b then print out that $a is greater than $b; if not (else) then print out $a is not greater than $b." It's also important to note that you don't say, "$a is less than $b," since it is possible that $a could be equal to $b. If that is the case, then the second part of the expression, the else statement, is the part that runs.

Note the use of brackets to enclose the actions. Also note the lack of semicolons where the brackets are used.

One final example is the if/elseif/else statement:

 if($a == $b) {      // do something } elseif ($a > $b) {     // do something else } elseif($a < $b) {     // do yet something else } else  {     // if nothing else we do this... } 

   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

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