RE: weird comparsion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 03 May 2007 12:30, OKi98 wrote:

> I know about identity operator (===) but with == operator 0 is false
> and "foo" is true

No, that's not correct.

  , try this:
> 
> $foo=0;
> $bar="bar";
> if ($foo) echo("$foo is true, ");
>     else echo("$foo is false, ");
> if ($bar) echo("$bar is true, ");
>     else echo("$bar is false, ");
> if ($foo==$bar) echo("$foo==$bar");
> 
> returns "0 is false, bar is true, 0==$bar"

That's because you've got loads of implicit type conversions going on there, so you're not comparing like with like.

For  if ($foo) ... and if ($bar) ...:

within the context of the if(), both $foo and $bar are implicitly converted to Boolean:
  - (bool)0 is FALSE
  - (bool)"any non-empty() string" is TRUE


On the other hand, for  if ($foo==$bar) ...:

in the context of the == comparison, $bar is converted to a number, and any string not beginning with a numeric character converts to numeric zero -- so you get a comparison of zero with zero, which is, of course, TRUE!

Or, in other words, (bool)$foo!==(bool)$bar, BUT (int)$foo===(int)$bar


It's exactly when you *don't* want this kind of automatic type-conversion shenanigans going on that you should use the === operator to make your intent entirely clear -- otherwise you have to be extremely aware of the context in which you are evaluating your variables in order to avoid hidden surprises like this.

Cheers!

Mike

---------------------------------------------------------------------
Mike Ford,  Electronic Information Services Adviser,
JG125, The Headingley Library,
James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS,  LS6 3QS,  United Kingdom
Email: m.ford@xxxxxxxxxxxxxx
Tel: +44 113 812 4730          Fax:  +44 113 812 3211 


To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm

[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux