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 ===
?
It depends entirely on the script you're writing, there's not one correct answer for this. Having said that, there aren't many situations where you don't already know the type of the variable (except perhaps user input).
This is the reason I stick to using
==
and only use===
when there could be more than one type of the variable.The
==
is fine most of the time, it wouldn't have been invented if you weren't supposed to use it :)if you're expecting that variable that you're passing will (and must) be integer than you should use triple equal, if not than you should avoid that.
Although, if you really want to use
===
than you should be doing conversion of variables to the type that you want along the way, like on this example:It depends on what you want to do.
Given that from forms, data comes as strings,
==
is handy because it can compare, for example, strings that represent numbers with numbers with no additional type casting.So no, it's not better to always use
===
.I would say it is better to always use
===
and remove one=
in cases you can justify.And yes it's equal, though weird. Better way to write it is
if(is_numeric($x) && $x == 1)
If you want such a strong validation, then the answer is: yes, definitely use
===
.The
==
also does some very weird things, like comparing completely different string as equal, just because they are numerically equivalent. So===
will probably be a better tool for you in most situations.This looks redundant to me. Why do we need to check if
$x
is_numeric
AND the value'1'
? We know'1'
is numeric so if it is equal to'1'
then it must be a number.You could use
===
comparison:If you're fine with interpreting it as a string:
or
If you must interpret the value as an
int
or
If you don't care about the actual type: