The if Statement

Just as in many other programming languages, PHP has if statements that you use when you need to carry out an action based on specific conditions.

if ( $age < 30 ) { 
  echo "Under thirty"; 
}

This will write out the phrase "Under thirty" but only if the value of the variable $age is less than 30.

The else Statement

PHP also has and else phrase.

if ( $age < 30 ) { 
  echo "Under thirty"; 
} else { 
  echo "Thirty or more"; 
}

The elseif Statement

If there are more than two possible actions then we can use the else if phrase.

if ( $age < 30 ) { 
  echo "Under thirty"; 
} elseif ( $age == 30) { 
  echo "Exactly thirty"; 
} else { 
  echo "More than thirty"; 
} 

For an equality test we use two equal signs, just like Javascript. With the else if phrase note the space between "else" and "if".

Compound Statements

The examples above all have a single test inside the if statement. Frequently, you will need to check multiple variables. While we can do this with multiple nested if statements this is not always preferable.

if ( $age < 30 ) {  
  if ($salary > 50000) {    
    //under 30 earning more than 50k  
  }
} else {
  if ($salary > 50000) { 
    //over 30 earning more than 50k 
  }
} 

In the above statement we are testing both the variable $age as well as the variable $salary. We could combine those tests into a single if statement if we wanted.

if ( $salary > 50000 && $age < 30 ) { 
  //under 30 earning more than 50k 
} elseif ( $salary > 50000 && $age > 30 ) { 
  //over thirty earning over 50k 
} 

We are doing the same test here but in a different format. This is a compound if statement. There are two tests inside the round brackets. They are separated with && which means AND. In the first line we check to see if the value of the variable $salary is greater than 50000 AND if the value of the variable is less than 30.

There is also an OR operator that we can use between tests. The OR operator is written as two pipe characters ||.

if ($salary > 50000 || $age > 30) { 
   //do something if the salary is over 50000 OR age is over 30 
}

This statement will do something if the value of $salary is over 50000 OR the value of $age is over 30.