奇怪的PHP字符串整数比较和转换 [英] Weird PHP String Integer Comparison and Conversion

查看:132
本文介绍了奇怪的PHP字符串整数比较和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些数据解析代码,而我遇到了以下情况。

I was working on some data parsing code while I came across the following.

$line = "100 something is amazingly cool";
$key = 100;

var_dump($line == $key);

我们大多数人都希望转储产生 false ,但令我惊讶的是转储是 true

Well most of us would expect the dump to produce a false, but to my surprise the dump was a true!

我知道在PHP中存在类似的类型转换:

I do understand that in PHP there is type conversion like that:

$x = 5 + "10 is a cool number"; // as documented on PHP manual
var_dump($x); // int(15) as documented.

但为什么我在第一个例子中提到的比较将我的字符串转换为整数而不是转换整数到字符串。

But why does a comparison like how I mentioned in the first example converts my string to integer instead of converting the integer to string.

我明白你可以对我的例子进行 === 严格比较,但我只是想要要知道:

I do understand that you can do a === strict-comparison to my example, but I just want to know:


  • PHP文档是否有任何部分提及此行为?

  • 可以有谁解释为什么在PHP中发生?

  • 程序员如何防止此类问题?

推荐答案

如果我正确地重新调整PHP'强制转换'两个变量到最低可能的类型。
他们称之为类型杂耍。

If I recal correcly PHP 'casts' the two variables to lowest possible type. They call it type juggling.

尝试: var_dump(something== 0); 例如,
,这会给你真实的。 。曾经咬过我一次。

try: var_dump("something" == 0); for example, that'll give you true . . had that bite me once before.

更多信息: http://php.net/manual/en/language.operators.comparison.php

这篇关于奇怪的PHP字符串整数比较和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆