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 ?
This question is related to
php
This is covered in the PHP documentation for booleans and type comparison tables.
When converting to boolean, the following values are considered FALSE:
FALSE
itself0
(zero)0.0
(zero)'0'
NULL
(including unset variables)Every other value is considered TRUE.
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.
Since I've visited this page several times, I've decided to post an example (loose) comparison test.
Results:
"" -> false
"0" -> false
"1" -> true
"01" -> true
"abc" -> true
"true" -> true
"false" -> true
0 -> false
0.1 -> true
1 -> true
1.1 -> true
-42 -> true
"NAN" -> true
0 -> false
-> true
null -> false
true -> true
false -> false
[] -> false
["a"] -> true
{} -> true
{} -> true
{"s":"f"} -> true
Code:
class Vegetable {}
class Fruit {
public $s = "f";
}
$cases = [
"",
"0",
"1",
"01",
"abc",
"true",
"false",
0,
0.1,
1,
1.1,
-42,
"NAN",
(float) "NAN",
NAN,
null,
true,
false,
[],
["a"],
new stdClass(),
new Vegetable(),
new Fruit(),
];
echo "<pre>" . PHP_EOL;
foreach ($cases as $case) {
printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 9, " ", STR_PAD_RIGHT), json_encode( $case == true ));
}
When a strict (===
) comparison is done, everything except true
returns false
.
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
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
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.
Source: Stackoverflow.com