PHP if statement

Description

We can make simple Decisions with the if Statement.

Syntax

The basic form of an if construct is as follows:


if (   expression  ) { 
  // Run this code /*from  ww  w  .  j  a v a 2 s .c  om*/
} 
// More code here   

If you only have one statement of code to execute, you can do without the braces entirely. It's a readability issue.

So, these two code chunks are the same:


if ($banned) {/* w w  w.j  ava 2s.  co m*/
       print "You are banned!";
}

if ($banned) print "You are banned!";

Note

If the expression inside the parentheses evaluates to true, the code between the braces is run.

If the expression evaluates to false, the code between the braces is skipped.

Example 1

Here is a working example for if statement:


<?php/*from w  w w.  ja  v a 2s . co  m*/
        $Age = 20;
        if ($Age < 18) {
                print "under 18\n";
        } else {
                print "You're not under 18\n";
        }
 ?>

The code above generates the following result.

Example 2

Here's another example that uses the >= (greater than or equal) and <= (less than or equal) comparison operators, as well as the && (and) logical operator:


<?PHP//  w  w w. j av  a2  s  .co  m
     $myValue = 23; 

     if ( $myValue  >= 10  &&  $myValue  <= 20 ) { 
       echo "between 10 and 20."; 
     }   
?>

Example nested if

Here's the previous example rewritten to use an if statement inside another if statement:


<?PHP//from w  w w . jav  a  2s  .  c o m
     $myValue = 23; 
     if ( $myValue  >= 10 ) { 
       if ( $myValue  <= 20 ) { 
         echo "10 and 20."; 
       } 
     }   
?>




















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition