I'm sure this has probably been covered here in the past, but I've
been unable to find a good way to search for it, so I'll just ask.

if( '20110204024217300000' === '20110204024217300264' )
  echo 'BAD';
else
  echo 'GOOD';

results in "GOOD" being echoed.

However,
if( '20110204024217300000' == '20110204024217300264' )
  echo 'BAD';
else
  echo 'GOOD';

results in "BAD" being echoed.

We guessed that probably the strings were both being converted to ints
for the comparison (even on a 64-bit platform 20-digit ints are too
large), and indeed the documentation says that "If you compare a
number with a string or the comparison involves numerical strings,
then each string is converted to a number and the comparison performed
numerically."

My questions are:
1) What is the advantage to converting both strings to ints to compare them?
We have code that compares values for updating in a database, and in
this case we were explicitly treating the data as strings, but don't
always do so. It was very non-obvious to us that comparing a
string-type to a string-type results in the type translation when
using ==.
It seems counter-productive to have to do:
if( (string) $a === (string) $b ) .....
in every circumstance where $a and $b are be strings representing very
large integers.
To be clear, I'm referring specifically to circumstances where the
type of the objects on both sides of the == comparison are the same.
(Maybe int-strings should be a special case, or perhaps this should
apply to any object type?)

2) The documentation
(http://www.php.net/manual/en/language.operators.comparison.php) only
mentions type juggling for ==, !=, and <>, but not greater-than or
less-than comparisons. Does this happen with those as well? (If so, I
think it could be helpful to have the documentation show this.)

3) If the expected/desired behavior is really to have both strings
converted to ints to do the comparison, it would make sense to me to
have a "loss of precision" warning- or something to that effect- when
the int exceeds the limits of PHP_INT_SIZE-byte ints. However, other
than backward compatibility, I have been unable to think of a reason
why two strings containing string-representations of ints should be
converted for the comparison-- especially with ==.

Thanks for your time everybody,
Matt

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to