If statements in PHP

If statements (conditional statements) are used to make decisions in your programs. An if statement will test a condition and then run a section of code if the condition evaluates to true. There are a number of relational operators and logical operators you can use in if statements to test different conditions which are explained in the video below.

Relational operators

Relational operators are used for comparison such as checking if one variable’s value is greater than another. Eg. is x greater than y? (x>y). Here is a list of relational operators:

Operator Description
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
=== identical to (equal to AND of the same data type)
!= not equal to
!== not identical to (not equal to AND not of the same data type)

Logical operators

Logical operators are used to combine conditions. Eg. is x greater than both y and also less than z? Here is a list of logical operators:

Operator Description
&& AND
|| OR
and AND (same as &&)
or OR (same as ||)
xor Xor (if either one or the other is true, but not both)
! NOT (eg. !$x returns true if $x is not true)

Watch the video and then scroll down to see the sample code.

Sample if statement PHP code:

<?php
 
 $number = 5;
 
 if($number < 10)
 {
 echo $number , " is less than 10";
 }
 
// comparison operators include < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (equal to), != (not equal to), and === (identical to).
?>

Sample PHP code using AND operator used to test that both criteria are true (the AND operator is two && ampersands):

<?php
 
 $number = 5;
 
 if($number > 1 && $number < 10)
 {
 echo $number , " is greater than 1 and less than 10.";
 }
 
 // logical operators include && (and) and || (or)
?>

Sample PHP code using OR operator to test that at least one criteria is true. (the OR operator is two || bars):

<?php
 
 $number = 5;
 
 if($number < 10 || $number > 20)
 {
 echo $number , " is less than 10 or greater than 20.";
 }
 
 // logical operators include && (and) and || (or)
?>

PHP Manual references: