NYCPHP Meetup

NYPHP.org

[nycphp-talk] comparison with zero

Dan Cech dcech at phpwerx.net
Fri Jul 21 10:32:59 EDT 2006


Scott Mattocks wrote:
> A non-empty string that is converted to a boolean will be converted to 
> TRUE. Also, the === operator converts all things to strings and then 
> compares the string values to see if the two are equal. Therefore, "str" 
> === 0 becomes "str" == "0" not 0 == 0.

Actually, no.

The === operator does not do any conversion at all, the 2 arguments must
have the same type and the same value for === to return true.

These pages from the manual will give you a good run down on how the
various comparison operators work.

http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/types.comparisons.php

If you want both arguments converted to string and compared as such you
will need to use the strcmp function:

http://php.net/manual/en/function.strcmp.php

Or do the conversion yourself:

if ((string)$a === (string)$b) {
  ...
}

The rules for comparisons are not altogether simple, and I for one found
my first thorough read-through of the pages above very enlightening.

Dan



More information about the talk mailing list