samedi 21 décembre 2019

Why does PHP consider a value of -1 to be true? Why isn't that "false" just like 0? [duplicate]

This question already has an answer here:

These both print "true":

$test = 1;

if ($test)
    echo 'true';
else
    echo 'false';

And:

$test = -1;

if ($test)
    echo 'true';
else
    echo 'false';

Only this one outputs "false":

$test = 0;

if ($test)
    echo 'true';
else
    echo 'false';

Why is "-1" considered "true"? If always forces me to do:

$test = -1;

if ($test > 0)
    echo 'true';
else
    echo 'false';

Which is very unintuitive to me, and uglier in many cases compared to if ($test).

Also, I'm pretty sure that this is some kind of standard behaviour which also happens in C and other languages, so I'm wondering in general about this design choice.

Aucun commentaire:

Enregistrer un commentaire