Page 1 of 1

zero, nothing, nil.

Posted: Thu May 29, 2008 8:16 am
by panic!
Something I've never understood about php is now it treats the int 0.

if you run the folowing code

Code: Select all

 
function insane($value)
{
    if($value==0)
    {
        print "matched";
    }
}
insane(0);
 
result: 'matched', great! As expected.

now run:

Code: Select all

 
function insane($value)
{
    if($value=='this')
    {
        print "matched";
    }
}
insane(0);
 
ok, bit weird: result: 'matched'

now try:

Code: Select all

 
function insane($value)
{
    if($value=='this')
    {
        print "this ";
    }
    if($value=='is')
    {
    print "is ";
    }
        if($value=='ridiculous')
    {
        print "ridiculous";
    }
}
insane(0);
 
somehow 0 is equal to 3 different things.

I've never understood this odd behaviour of php, that all strings are 0, is that because a string has 0 value?

Re: zero, nothing, nil.

Posted: Thu May 29, 2008 8:54 am
by VladSun
I think it's because intval($value) will return 0 for none numerical strings.
Try

Code: Select all

if($value === 0 )
also, I think that it would be more appropriate if intval() would return 'false' on failure, but ...

Re: zero, nothing, nil.

Posted: Thu May 29, 2008 9:15 am
by dml
The rules being followed are:

1: when comparing a string and an int for equality, convert the string to an int: 0==(int)"this"
2: non-numeric strings are converted to 0: 0==0

== isn't a mathematical equivalence relation. It's symmetric: if $a==$b then $b==$a, and reflexive: $a==$a, but it's not transitive: you can have $a==$b and $b==$c without $a==$c: "foo"==0, 0=="bar", but "foo"!="bar".

I suppose rather than a mathematical logic it's a scripting language logic, where the system makes a best effort to automatically convert to and from textual representations of data.

There is a stricter === that's a more mathematical kind of equality.