PHP if Operators

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.

Tutorials dojo strip

Comparison Operators

Comparison operators are used within if statements to compare two values.

Example 1: Basic Comparison

Check whether $gear is equal to 6:

PHP

To compare values effectively, you need to use one of PHP’s comparison operators, as detailed below:

OperatorNameResult
==EqualReturns true if the two values are the same
===IdenticalReturns true if the two values and their data types are exactly the same
!=Not EqualReturns true if the two values are not the same
<>Not EqualReturns true if the two values are not the same (alternative to !=)
!==Not IdenticalReturns true if the values or their data types differ
>Greater ThanReturns true if the first value is larger than the second
<Less ThanReturns true if the first value is smaller than the second
>=Greater or EqualReturns true if the first value is greater than or equal to the second
<=Less or EqualReturns 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:

PHP

PHP provides several logical operators for combining conditions:

OperatorNameDescription
andAndReturns true if both conditions are true
&&AndReturns true if both conditions are true
orOrReturns true if at least one condition is true
||OrReturns true if at least one condition is true
xorXorReturns true if only one condition is true (not both)
!NotReturns 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:

PHP

In this example, the || operator checks whether $modelYear matches any of the specified years.

Tutorials dojo strip