【问题标题】:PHP Comparison Operators and Data TypesPHP 比较运算符和数据类型
【发布时间】:2010-12-16 22:45:55
【问题描述】:

我目前正在研究 O'Reilly 的“PHP 编程”,并遇到了这个标题为“比较运算符执行的比较类型”的表格:

第一个操作数 |第二个操作数 |比较 -------------------------------------------------- --------------------- 号码 |号码 |数字 数字字符串 |数字字符串 |数字 数字字符串 |号码 |数字 非数字字符串 |号码 |辞典 数字字符串 |非数字字符串 |辞典 非数字字符串 |非数字字符串 |辞典

对于执行哪种类型的比较,我的经验法则是“当且仅当至少一个操作数是数字或两个操作数都是数字字符串时是数字的”。 php.net page on Comparison Operators 似乎支持这一点,其中指出“如果将整数与字符串进行比较,则字符串将转换为数字。如果比较两个数字字符串,则将它们作为整数进行比较。”

但是,这意味着表格第四行中的比较应该是“数字”。表格是否包含错误,还是我的规则有误?

【问题讨论】:

  • 你的规则是错误的。尝试比较"string" == 0intval("string") == 0
  • @Ast Derek:两个比较的结果似乎都是真的。

标签: php comparison operators


【解决方案1】:

已编辑:基于 cmets 的完整面孔。

您的总结是正确的,而表格是错误的。如果一个操作数是数字,则尝试对字符串开头的数字位进行转换。如果没有数字前导,则转换返回零。转换发生在小数和计算的有理结果,而不仅仅是整数。

下面的代码演示了这些行为

if (2 > '10 little pigs') print 'Integer does not coerce string'."\n"; else print 'Integer does coerce string'."\n"; if (2.5 > '10 little pigs') print 'Decimal does not coerce string'."\n"; else print 'Decimal does coerce string'."\n"; if (5/3 > '2 little pigs') print 'Rational result does not coerce string'."\n"; else print 'Rational result does coerce string'."\n"; if (0 == 'No little pigs') print 'Non numeric coerced to zero'."\n"; else print 'Non numeric not coerced'."\n"; if (-0.156 > '-127 is a minumum value of a signed 8 bit number') print 'Negative decimal does coerce string'."\n"; else print 'Negative decimal does not coerce string'."\n"; if ('-0.156' > '-127') print 'Both are converted if all numeric'."\n"; else print 'No conversion if both are all numeric'."\n"; if ('-0.156' > '-127 is a minumum value of a signed 8 bit number') print 'Successful conversion of one does coerce the other'."\n"; else print 'Successful conversion of one does not coerce the other'."\n";

【讨论】:

  • php.net 语句说“如果将整数与字符串进行比较,则字符串将转换为数字。”这是否意味着整数与字符串(任何字符串,无论是否为数字)的比较是数字的?这与您的“翻译”不一致。
  • 重新阅读 php.net 页面,您引用的表格和页面之间的术语似乎不匹配。似乎并非所有数字的行为都相同。我正在尝试为该案例编写一段演示代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2012-02-22
  • 2011-02-03
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多