2
votes

I'm currently working through O'Reilly's "Programming PHP" and have come across this table titled "Type of comparison performed by the comparison operators":

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

My rule of thumb for which type of comparison is performed has been "numeric if and only if at least one operand is a number or both operands are numeric strings". This seems to be supported by the php.net page on Comparison Operators, which states "If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers."

However, this would imply that the comparison in the fourth row of the table should be "Numeric". Does the table contain an error, or is my rule wrong?

1
Your rule is wrong. Try comparing "string" == 0 and intval("string") == 0Ast Derek
@Ast Derek: The result of both comparisons seems to be true.user200783

1 Answers

3
votes

Editted: A complete about face based on the comments.

Your summary is correct, and the table is wrong. A conversion is attempted on the numeric bit at the start of the string if one operand is numeric. The conversion returns zero if there is no numeric leader. The conversion takes place for decimals and the rational results of calculations, not just integers.

The code below demonstrates the behaviours


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