Reputation:
I have a technical question which need expert advise. I have a data in the database which is a string "true". But when I retrieve it to test the condition, which one is more advisable to use even though they both work.
if ($data == true)
or
if ($data == "true")
My gut feeling is use "true" to test if the value stored is a string and use true without the quotes when the database value is stored as a boolean. But want to confirm with you guys.
Thanks...
Upvotes: 1
Views: 135
Reputation: 11711
"false"==true
is true.
If your database has a column that only has the values of "true" or "false" then that is inefficient. Convert the column to a tinyint (or bool).
Otherwise, you should consider switching the string values of "true"
and "false"
to the boolean values of true
and false
when you pull them out of the database.
Upvotes: 0
Reputation: 1372
If the value is stored literally as a string in the db, the second (if ($data = "true")
) is what you want though they both will work. I suggest the second one for clarity.
You can test this out on the command using an interactive shell.
php -a
Interactive shell
php > $x = "true";
php > echo ($x == true) ? "True!" : "oops";
True!
php > echo ($x == "true") ? "True!" : "oops";
True!
php > echo ($x === "true") ? "True!" : "oops";
True!
php > echo ($x === true) ? "True!" : "oops";
oops
Note the effect that the ===
has. Since the value is a string they are not equal when using ===
.
Upvotes: 0
Reputation: 179086
The important case to understand is what the value will be from the database if the value is supposed to be false
.
If the database returns "false"
, and you check $val == true
and $val == "true"
only the latter will provide correct results.
You may need to consult the php type comparison tables to be certain you understand what it is you're checking against.
Additionally, is there any chance that the database could return one of the following?
"true"
"True"
"TRUE"
"TrUe"
Just normalize or sanitize your database values (ideally, store binary values in a Boolean field so that this isn't necessary.
Upvotes: 0
Reputation: 197832
Confirmed, at least almost. You're right to check the data-type as well, however in PHP you need to use the ===
operator for that:
if ($data === TRUE) # boolean
if ($data === "true") # string
It's called the identical operator Docs and it compares the value and the type. Often helpful.
Upvotes: 4
Reputation: 4448
If it is a string then $data == "true"
is what you want.
The expression ($data == true)
is equivalent to ($data)
, so it will evaluate to true
even when $data == "false"
Upvotes: 1