I searched on StackOverflow and Google and I can't find the answer to this question:
Should we always use the triple equal in PHP for validation?
For example, I have a variable:
$x = '1';
if($x == 1) // will work
if($x === 1) // will not
Now, my point is if we need to validate numeric fields like:
if(is_numeric($x) && $x == '1') {
will be the equivalent to if($x === 1)
Since ===
also validate the type, will it be better if we always use the ===
?
The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.
Identical Operator ===The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false.
Turns out, the difference between them is the double equals allows coercion and the triple equals disallows coercion. They both test equality. One of them allows coercion to occur first and one of them doesn't.
KEY DIFFERENCES:= does not return true or false, == Return true only if the two operands are equal while === returns true only if both values and data types are the same for the two variables.
From http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/
== is useless.
‣ It’s not transitive. "foo" == TRUE, and "foo" == 0… but, of course, TRUE != 0.
‣ == converts to numbers when possible, which means it converts to floats when possible. So large hex strings (like, say, password hashes) may occasionally compare true when they’re not. Even JavaScript doesn’t do this.
‣ For the same reason, "6" == " 6", "4.2" == "4.20", and "133" == "0133". But note that 133 != 0133, because 0133 is octal.
‣ === compares values and type… except with objects, where === is only true if both operands are actually the same object! For objects, == compares both value (of every attribute) and type, which is what === does for every other type. What.
See http://habnab.it/php-table.html
And http://phpsadness.com/sad/47
And http://developers.slashdot.org/comments.pl?sid=204433&cid=16703529
That being said, when you are absolutely sure type is not an issue when you are creating simple expressions, == works well enough in my experience. Just be vigilant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With