In PHP, the if
statement often relies on comparison operators and logical operators to evaluate conditions. These operators help determine whether certain conditions are true or false, enabling your code to execute specific actions accordingly.
Comparison Operators
Comparison operators are used within if
statements to compare two values.
Example 1: Basic Comparison
Check whether $gear
is equal to 6
:
$gear = 6;
if ($gear == 6) {
echo "You're riding at top gear!";
}
To compare values effectively, you need to use one of PHP’s comparison operators, as detailed below:
Operator | Name | Result |
---|---|---|
== | Equal | Returns true if the two values are the same |
=== | Identical | Returns true if the two values and their data types are exactly the same |
!= | Not Equal | Returns true if the two values are not the same |
<> | Not Equal | Returns true if the two values are not the same (alternative to != ) |
!== | Not Identical | Returns true if the values or their data types differ |
> | Greater Than | Returns true if the first value is larger than the second |
< | Less Than | Returns true if the first value is smaller than the second |
>= | Greater or Equal | Returns true if the first value is greater than or equal to the second |
<= | Less or Equal | Returns true if the first value is less than or equal to the second |
Logical Operators
Logical operators allow you to evaluate multiple conditions within a single if
statement.
Example 2: Combining Conditions
Check if $speed
is greater than $minimum
and less than $maximum
:
$speed = 90;
$minimum = 60;
$maximum = 120;
if ($speed > $minimum && $speed < $maximum) {
echo "You're driving at a safe speed.";
}
PHP provides several logical operators for combining conditions:
Operator | Name | Description |
---|---|---|
and | And | Returns true if both conditions are true |
&& | And | Returns true if both conditions are true |
or | Or | Returns true if at least one condition is true |
|| | Or | Returns true if at least one condition is true |
xor | Xor | Returns true if only one condition is true (not both) |
! | Not | Returns true if the condition is false |
Checking Multiple Conditions
You can chain together multiple conditions using logical operators for more complex evaluations.
Example 3: Multiple Comparisons
Determine if $modelYear
falls within a range:
$modelYear = 2021;
if ($modelYear == 2019 || $modelYear == 2020 || $modelYear == 2021 || $modelYear == 2022) {
echo "This is a recent car model.";
}
In this example, the ||
operator checks whether $modelYear
matches any of the specified years.