简体   繁体   English

检查未知类型数是否为0的最安全方法是什么? AKA为什么float(0)不等于(int)0?

[英]What's the safest way to check if a number of unknown type is 0? AKA Why float(0) is not equal to (int)0?

Can someone help me understand why this happens? 有人可以帮我理解为什么会这样吗?

$zero = (float)0;
var_dump($zero);
var_dump(0);
var_dump( ($zero === 0) );

This produces: 这将产生:

float(0)
int(0)
bool(false)

I don't really understand why, I am aware of the giant red warning here , but isn't 0 supposed to be 0? 我真的不明白为什么,我知道这里有红色的大警告,但是0不应该是0吗? Or is PHP actually comparing the variable type (float against int)? 还是PHP实际上在比较变量类型(float与int)?

Assuming that's the case, what is the safest way to check if a number (not knowing its exact type) is 0? 假设情况如此,检查数字(不知道其确切类型)是否为0的最安全方法是什么?

Thanks. 谢谢。

int(0) is same as float(0) , just that when you use === then type, as well as value, is compared. int(0)float(0)相同,只是当您使用===时,将比较类型和值。 In this case value is same but type is different, hence its false . 在这种情况下,值相同,但类型不同,因此其false Those values are Equal but not Identical . 这些值Equal但不Identical

int(0) == float(0)    // true because only value is compared, which is same.
int(0) === float (0)  // false because even though value is same, type is also compared, which is different

$a === $b 'Identical' TRUE if $a is equal to $b, and they are of the same type. $ a === $ b'相同'如果$ a等于$ b,并且它们是同一类型,则为TRUE。
$a == $b 'Equal' TRUE if $a is equal to $b after type juggling. $ a == $ b'等于'如果类型变戏法后$ a等于$ b,则为TRUE。

Reference: 参考:

A good way to test whether numeric value of your variable is 0 would be: 测试变量的数值是否为0的一种好方法是:

if (intval($zero)==0)
{
  // $zero is 0 in numeric terms. You can even send it a string to test, which will be 0
}

Read http://php.net/manual/en/types.comparisons.php 阅读http://php.net/manual/en/types.comparisons.php

=== compares type as well as value. ===比较类型和值。 If you just want to compare value then use == 如果您只想比较值,请使用==

$zero = (float)0;
var_dump($zero);
var_dump(0);
var_dump( ($zero === 0) );
var_dump( ($zero == 0) );

Will return float(0) int(0) bool(false) bool(true) 将返回float(0)int(0)bool(false)bool(true)

it's because === compares types and value and == compares only values 这是因为===比较类型和值,而==仅比较值

$foo = 0;

var_dump((float)$foo==(int)$foo); //Produces true

var_dump((float)$foo===(int)$foo); //Produces false

Actually their are two comparative operators 其实他们是两个比较算子

== checks only for equality of values ==仅检查值是否相等

=== checks the equality of both type and the value. ===检查类型和值的相等性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM