zero, nothing, nil.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
panic!
Forum Regular
Posts: 516
Joined: Mon Jul 31, 2006 7:59 am
Location: Brighton, UK

zero, nothing, nil.

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: zero, nothing, nil.

Post 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 ...
There are 10 types of people in this world, those who understand binary and those who don't
dml
Forum Contributor
Posts: 133
Joined: Sat Jan 26, 2008 2:20 pm

Re: zero, nothing, nil.

Post 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.
Post Reply