Type-casting to boolean

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.


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);

I use this way:

!!0 (false)
!!1 (true)

filter_var - Filters a variable with a specific filter

$boolvar = filter_var('true', FILTER_VALIDATE_BOOLEAN);

boolval - Get the boolean value of a variable PHP 5 >=

$boolvar = boolval ('true');

And literally with a ternary operator but I can't recommend it

$boolvar = ($string === 'true')  ? true: false;