Double equals and tripple equals in php

2020-04-04 10:20发布

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 ===?

标签: php
7条回答
三岁会撩人
2楼-- · 2020-04-04 10:50

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.

查看更多
登录 后发表回答