The PHP equal sign can be used to assign the value of variable as well as evaluate a variable as part of an if-else statement or other conditional statement. However, there are subtle differences that are important for ensuring your PHP code is as accurate as possible. The following samples are from page 22.
The Equal Sign
Assignment ( = ): Assigns the value on the right to the variable on the left
Equality ( == ): Checks if the left and right values are equal
Identical ( === ): Checks if the left and right values are equal AND identical (same variable type)
Example:
$a = 1; // Sets the value of $a as the integer 1 $b = TRUE; // Sets the value of $b to the boolean TRUE if ($a == $b){ echo 'a is equal to b.'; } if ($a === $b){ // compare VALUE and data type: if $a(integer) === $b(boolean) echo 'a is identical and equal to b.'; } |
a is equal to b.
Not ( ! ), Not Equal to ( != ), Not Identical to ( !== )
Used in conditional statements to evaluate as true a FALSE result of an expression or if a value is NOT equal to the second value.
Example:
$a = 1; if (!isset($a)){ // If the variable $a is NOT set then... echo '$a is not set'; // The expression is TRUE if it is NOT set // Since there is no ELSE statement, nothing is displayed } if ($a != 0){ echo '$a does not equal zero'; } |
$a does not equal zero
Thanks, now I understand that double equal signs compare while triple equals signs compare if identical data type in addition to the value
Matt,
I was left wondering what the diff was until I read your comment. Thank you for making that clear. Hope they add that info to the article.
“Identical ( === ): Checks if the left and right values are equal AND identical”
It is also worth clarifying that the word “identical” is referring to comparison of variable data types. While using double equal signs (==) is appropriate for comparing the contents of two variables, using triple equal signs (===) is intended not only for comparing the contents of two variables, but comparing the data type (or the type of each variable).
The first example was a good illustration of this in the comments where variable $a is assigned an integer (int) value of 1 and variable $b was assigned a boolean (bool) value of TRUE.
Always remember that the data type of a variable is being set automatically by the *type* of value you assign it, whether it be integer (int), floating point (float), associative array (array), boolean (bool), class object (object) or even a resource (as in the case of MySQL queries). Therefore, use of the triple equal sign (===) for comparison is most appropriate when data types matter.
Thanks for the reference, I’m working on a php project.