Comparison Operators
A condition usually comes down to comparing two values, and that is the job of comparison operators.
Equal Operator
Use == to test whether two values are equal. The result is true when they are:
Prompt
Write a PHP script that uses the == operator to check if a variable equals a value and prints a message if true.
Output: PHP script
index.php
<?php
$x = 100;
if ($x == 100) {
echo "x is equal to 100";
}
?>
Greater Than Operator
With >, you get true when the value on the left is the bigger of the two:
Prompt
Write a PHP script that uses the > operator to check if one variable is greater than another and prints a message.
Output: PHP script
index.php
<?php
$x = 100;
$y = 50;
if ($x > $y) {
echo "x is greater than y";
}
?>
Less Than Operator
With <, it works the other way round: the result is true when the value on the left is the smaller one:
Prompt
Write a PHP script that uses the < operator to check if one variable is less than another and prints a message.
Output: PHP script
index.php
<?php
$x = 10;
$y = 50;
if ($x < $y) {
echo "x is less than y";
}
?>
Logical Operators
To build one condition out of several smaller ones, you need logical operators.
And Operator
&& gives true only when the conditions on both sides are true:
Prompt
Write a PHP script that uses the && operator to check if two conditions are both true and prints a message.
Output: PHP script
index.php
<?php
$x = 100;
$y = 50;
if ($x > 10 && $y < 80) {
echo "Both conditions are true";
}
?>
Or Operator
|| needs just one true condition, though both may be true:
Prompt
Write a PHP script that uses the || operator to check if at least one of two conditions is true and prints a message.
Output: PHP script
index.php
<?php
$x = 100;
$y = 50;
if ($x > 90 || $y > 80) {
echo "At least one condition is true";
}
?>
Not Operator
! flips a condition, so the if block runs when the condition in the parentheses is false:
Prompt
Write a PHP script that uses the ! operator to check if a condition is not true and prints a message.
Output: PHP script
index.php
<?php
$x = 100;
if (!($x < 50)) {
echo "x is NOT less than 50";
}
?>