Hi,
I wonder how PHP handles true/false comparison internally. I understand that true is defined as 1 and false is defined as 0. When I do if("a"){ echo "true";} it echos "true". How does PHP recognize "a" as 1 ?
Hi,
I wonder how PHP handles true/false comparison internally. I understand that true is defined as 1 and false is defined as 0. When I do if("a"){ echo "true";} it echos "true". How does PHP recognize "a" as 1 ?
Zero is false, nonzero is true.
In php you can test more explicitly using the === operator.
if (0==false)
echo "works"; // will echo works
if (0===false)
echo "works"; // will not echo anything
This is covered in the PHP documentation for boolean.
When converting to boolean, the following values are considered FALSE:
Every other value is considered TRUE.
PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.
other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.
PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.
The best operator for strict checking is
if($foo === true){}
That way, you're really checking if its true, and not 1 or simply just set.