php -a
Interactive shell
php > var_dump("some" == 0);
bool(true)
php > var_dump("some" == false);
bool(false)
php > var_dump("some" == true);
bool(true)
php > var_dump(false == 0);
bool(true)
My question is simple. What is the reasoning behind ("some" == 0) === true
? I understand that due to the weak typing the operands are converted to something comparable. But in this particular example it's against how I understand it.
If the zero would be converted to string it would be:
php > var_dump("some" == "0");
bool(false)
If it was converted to bool, it would be:
php > var_dump("some" == false);
bool(false)
Only sensible explanation is:
php > var_dump(intval("some"));
int(0)
php > var_dump(intval("some") == 0);
bool(true)
But that's certainly not what I or anyone would expect. Especially because any string would be turned to zero (and that potentially means false in any comparison).
Why is it this way?
Update:
My question was more about "why" not "if" or "how", sorry if that was not quite obvious. And I think I found my answer in Why PHP casts two numerical strings to numbers before [loosely] comparing them?
Simples
php > var_dump("some" == 0);
The string "some" is cast to an integer for comparison with an integer, and will be cast to a 0
in this case.
0 == 0
is true
If the string "13 monkeys" was cast to an integer, it would be a value of 13
php > var_dump("13monkeys" == 0);
13 == 0
is false
The rules for casting a string to a number are explained in the PHP docs