简体   繁体   English

PHP if / else问题使用true / false

[英]PHP if/else issue using true/false

My code looks like this: 我的代码如下所示:

$muted = 'true'; //Note this is only for testing
if ($muted == 'false' || $muted == '' || $do_not_text == '' || $do_not_text =='false'){
//do this first thing
}
else{
//do something else
}

I can't get my else to run. 我不能让else跑。 What syntax am I messing up? 我搞砸了什么语法?

Related to this, I'm storing a value in my database (that will be what's called to set $muted in my real code) that's either 'true', 'false', or ''. 与此相关的是,我在数据库中存储了一个值(即在我的真实代码中设置$muted ),即“ true”,“ false”或“”。 What data type should I be storing these as? 我应该将这些数据存储为什么数据类型? Currently, I'm using VARCHAR , but I suspect this is all part of the problem. 当前,我正在使用VARCHAR ,但是我怀疑这是问题的全部。

$do_not_text == '' evaluates to true. $do_not_text == ''评估为true。 Why? 为什么? Because $do_not_text is not defined which is a falsy value. 因为未定义$do_not_text ,这是一个伪造的值。 You are comparing it to an empty string which also equates to a falsy value. 您正在将其与一个空字符串进行比较,该字符串也等于一个伪造的值。 So that comparison is true causing the first if statement to be evaluated as true. 这样的比较是正确的,导致第一个if语句被评估为true。

I'm not sure why you're using strings for what should be boolean values. 我不确定为什么要使用字符串作为布尔值。

$muted = true; // no need for quotes

You might also consider using the === operator when comparing boolean values. 比较布尔值时,您可能还考虑使用===运算符。

if ($muted === false || // etc...

What data type should I be storing these as? 我应该将这些数据存储为什么数据类型?

Boolean values in MySQL are typically stored as 1 or 0. MySQL中的布尔值通常存储为1或0。

field_name TINYINT(1) UNSIGNED NOT NULL DEFAULT 0

Store them as TINYINT with length of 1 because its only 1 and 0, and 0 as the default value. 将它们存储为TINYINT ,长度为1因为它只有1和0,默认值为0

Then you can make $muted = boolval($db_muted_val); 然后可以使$muted = boolval($db_muted_val); if you want, or use $db_muted_val as is, because 1 is true and 0 is false . 如果需要,或$db_muted_val原样使用$db_muted_val ,因为1true0false

if ($db_muted_val) {
    // do this first thing
} else {
    // do something else
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM