Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String compare on a bool

I'm pretty sure this is a simple fundamental flaw in my newb PHP knowledge, but I was surprised when the following happened:

enter image description here

$result is TRUE... so why is it considered equal to the string "email"? I'm guessing this is because, technically, it's a bool and it isn't false? So when it's compared against a string (e.g. "email") it returns true.

Should I change my method to return as the result as a string containing "true" (instead of return true; on success), or is there another way I should be doing this?

Thanks.

like image 707
Chuck Le Butt Avatar asked May 09 '11 14:05

Chuck Le Butt


People also ask

Can boolean compare strings?

Control Statements. Boolean expressions. Compare strings. In Java, syrings are compared character by character, starting with the first character and using the Unicode collating sequence.

How do you compare boolean values with strings?

Using the Strict Equality Operator (===) In this method, we will use the strict equality operator to compare strings to Boolean. The strict equality always returns false when we compare string and boolean values as it also checks for the data type of both operands.

Can you use == with boolean?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".

How do you compare a boolean to a string in Python?

You can use the boolean operators "==" and "! =" to compare two strings. You can use the "==" operator to test strings for similarity and the "! =" operator to check strings for inconsistencies.


2 Answers

Yes, true is equal (==) to a non-empty string. Not identical (===) though.

I suggest you peruse the type comparison table.

like image 193
deceze Avatar answered Sep 20 '22 00:09

deceze


It returns true because php will try to convert something to be able to compare them. In this case it probably tries to convert the string on the right side to a bool which will be true in this case. And true == true is ofcourse true.

By doing $result === "email" (triple =) you tell PHP that it shoudn't do conversions and should return false if the types don't match.

like image 21
Eelke Avatar answered Sep 22 '22 00:09

Eelke