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:25

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 :)

查看更多
地球回转人心会变
3楼-- · 2020-04-04 10:30

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:

if ((int) $var === 1)
{

    // will return true if the $var is 1
}
查看更多
叛逆
4楼-- · 2020-04-04 10:32

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.

if ($_GET['amount'] == 10) {
    //...
}

So no, it's not better to always use ===.

查看更多
叛逆
5楼-- · 2020-04-04 10:40

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)

查看更多
趁早两清
6楼-- · 2020-04-04 10:45

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.

查看更多
Summer. ? 凉城
7楼-- · 2020-04-04 10:49
if (is_numeric($x) && $x == '1') { ...

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:

if ($x === '1') { ...

or

If you must interpret the value as an int

if ((int) $x === 1) { ...

or

If you don't care about the actual type:

if ($x == '1') { ...
查看更多
登录 后发表回答