PHP比较运算符和数据类型

时间:2009-11-16 05:22:26

标签: php comparison operators

我目前正在使用O'Reilly的“Programming PHP”,并且遇到了这个名为“比较运算符执行的比较类型”的表:

First Operand              | Second Operand             | Comparison
-----------------------------------------------------------------------
Number                     | Number                     | Numeric
String that is numeric     | String that is numeric     | Numeric
String that is numeric     | Number                     | Numeric
String that is not numeric | Number                     | Lexicographic
String that is numeric     | String that is not numeric | Lexicographic
String that is not numeric | String that is not numeric | Lexicographic

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

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

1 个答案:

答案 0 :(得分:3)

编辑:基于评论完整的面孔。

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

以下代码演示了行为


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";