Tutorial 14: Comparison Operators


At this point, we've been playing with PHP Variables, Arrays, and If Statements. In nearly every lecture so far, we've seen the "=" symbol. You probably have a basic understanding that it sets a value to a variable, like so:

$myName = "Brad";

In the PHP world, the = symbol is called an "assignment operator". It basically "assigns" the value on the right to the variable on the left. There are many assignment operators, but we'll get into those once we've been introduced to the many other types of operators in PHP.

First, we will start with the "comparison operator".

Comparison operators allow you to compare multiple elements. You can compare whether elements are:

Here is a handy table, provided by PHP.net

Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only). You're using PHP 7.2.22.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Here is an example of how you would use one of the above comparison operators:

$yearsOnEarth = 14;

if ($yearsOnEarth <= 25) {
	
	echo "Your age is less than or equal to 25!";
	
}

Feel free to experiment with all of the above comparison operators with some PHP If / Else / Elseif statements using the practice.php page provided in this folder.

Check out the final example
©2019 Brad Hussey