0

我对这个相等的运算符有点困惑。

回声 (2 == "2.5time")

应输出为 1/true。

"2.5time" 字符串应类型转换为整数并输出 2 作为整数。

但它似乎没有输出任何东西。

谁能解释一下?

4

4 回答 4

4

如果它没有输出任何表示错误的东西,请执行 var_dump(2 == "2.5time") 以查看发生了什么。

于 2012-09-21T19:48:04.517 回答
2

比较是让 PHP 解析字符串并获得 2.5 的数字,这是一个浮点数。然后将其与您的整数进行比较,该整数被视为浮点数 2.0

于 2012-09-21T19:55:00.740 回答
1

如果您希望将字符串开头的数字作为整数处理,则必须将它们类型转换为整数,因此

if(2 == (int)"2.5times") // will be true
于 2012-09-21T19:59:24.967 回答
0

如果使用 == 运算符,它将比较所有的字符串。

(2 == "2") // is true, because is the same value
(2 === "2") // is false, because is the same value, but is different types
(2 == "23") // is false, contains different values

但在您的情况下,最好使用strpos在字符串中查找子字符串。

于 2012-09-21T19:54:48.347 回答