Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-casting to boolean

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?

like image 690
Paris Liakos Avatar asked Dec 05 '11 02:12

Paris Liakos


People also ask

Can you typecast a boolean?

You cannot cast it because it cannot be cast.

Can we cast any other type to boolean type with type casting?

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.

How do you convert numbers to boolean?

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”.

How do you convert boolean to TypeScript?

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.


2 Answers

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); 
like image 155
ruakh Avatar answered Oct 03 '22 01:10

ruakh


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.

like image 35
Jon Avatar answered Oct 03 '22 01:10

Jon