PHP if

In this chapter you will learn:

  1. What is an if statement
  2. Syntax for if statement
  3. Note for if statement
  4. Example - if statement
  5. Example - if statement with more conditions

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  jav a  2 s .  c o  m*/
} 
// 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) {//from   java2s.c o  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  jav  a2 s  .c o  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/*from j  a va  2 s .c o  m*/
     $myValue = 23; 

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

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


<?PHP//java  2  s .com
     $myValue = 23; 
     if ( $myValue  >= 10 ) { 
       if ( $myValue  <= 20 ) { 
         echo "10 and 20."; 
       } 
     }   
?>

Next chapter...

What you will learn in the next chapter:

  1. Description for if else statement
  2. Syntax for if else statement
  3. Note for if else statement
  4. Example - PHP if else statement
  5. Example - PHP if else statement ladder
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require