Can someone explain me why this:
var_dump((bool) 1==2);
returns
bool(true)
but
var_dump(1==2);
returns
bool(false)
Of course the second return is correct, but why in the first occasion php returns an unexpected value?
You cannot cast it because it cannot be cast.
Casting between primitive types enables you to convert the value of one type to another primitive type is called Primitive Type Casting. This is most commonly occurs with the numeric data types . But boolean primitive type can never be used in a cast.
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.
It's actually not as strange it seems. (bool)
has higher precedence than ==
, so this:
var_dump((bool) 1==2);
is equivalent to this:
var_dump( ((bool) 1) == 2);
or this:
var_dump(true == 2);
Due to type juggling, the 2
also essentially gets cast to bool
(since this is a "loose comparison"), so it's equivalent to this:
var_dump(true == true);
or this:
var_dump(true);
Because in the first example, the cast takes place before the comparison. So it's as if you wrote
((bool) 1)==2
which is equivalent to
true == 2
which is evaluated by converting 2
to true
and comparing, ultimately producing true
.
To see the expected result you need to add parens to make the order explicit:
var_dump((bool)(1==2));
See it in action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With