Operators in PHP are of different types, such as:
These operator types have a list of different operators which have different functions. In this Answer, we will look at some operators in the assignment and comparison types.
=
operatorThis equal sign is usually known as the assignment operator. It assigns the value of what is at the right side of an expression to the left side.
Let’s see the code example of the =
operator.
<?php$aFew =2;$some = 4;$many = $some + $aFew;echo $aFew .',';echo $some .',';echo $many;?>
The equality sign only takes a variable and assigns it to another variable or a value.
==
operatorThis is a comparison operator that will return either true
or false
by comparing the values of variables on both sides.
It returns
true
when the values on both sides are the same. Otherwise,false
is returned.
Let’s understand the ==
operator with a code example.
<?php$aFew = 4;$some = "4";if($some == $aFew ){echo "The value on both sides are same.";}?>
In the code above, you see that logically 4
cannot be equal to "4"
. But with the ==
operator, it is evaluated as true
. The ==
operator simply matches the values of the two variables and does not consider what data type they are.
===
operatorThe triple equal sign comparison operator not only checks if the variables are equal in value, but it also confirms that they are of the same type before it returns true
or false
.
Let’s see how the ===
operator works and is different from other operators.
<?php$aFew = 4;$some = 4;$many = "4";if($some === $many ){echo "Two values are same";}if($some === $aFew ){echo "Two values are same";}/*the first if() statement evaluated as 'false'so it didn't execute our echo statement*/?>
=
operator only assigns values.==
does not assign values, but compares them without checking their data types.===
won’t do assignment, but will check for equality of values and the data type.