PHP Basics : Comparison operators
Understanding what comparison operators are available in PHP code and when to use them for best results.
PHP comparison operators aren’t that much different from comparison operators in any other language but can be a cause of issues for new users due to the script comparison as well as the difference between equal and identical.
Let’s look at some basic comparison operators.
$a = 10;var_dump($a == 10);
var_dump($a == '10');
The above comparison operators are equal operators. This means it will evaluate the expression, ignoring types for equality. Strings will be converted to integers and vice-versa.
With that understood, the output of this code would be:
bool(true) // 10 is equal to 10
bool(true) // 10 is equal to '10'
If we wrote those comparisons instead using the identical comparison operator, then it will compare the type.
var_dump($a === 10);
var_dump($a === '10');
As you can see, we’ve used === this time instead of the == from before. This specifies that we want an identical comparison and it will compared the type of the variable. In this case the output is:
bool(true); // 10 is identical to 10
bool(false); // 10 is not identical to '10'