【问题标题】:How does php cast boolean variables?php如何转换布尔变量?
【发布时间】:2010-12-16 03:56:27
【问题描述】:

php如何转换布尔变量?

我试图将布尔值保存到数组中:

$result["Users"]["is_login"] = true;

但是当我使用调试时 is_login 值是空白的。 当我做这样的条件时:

if($result["Users"]["is_login"])

条件总是错误的。

然后我尝试这样做:

$result["Users"]["is_login"] = "true";

它成功了。

这没什么大不了的,但是当我从函数返回布尔值时,我仍然需要将它们转换为字符串。

【问题讨论】:

  • 您是在序列化、转换为 JSON 还是介于两者之间?如果不是,则不应涉及强制转换——您将一个值存储在一个数组中,而数组不关心它们包含什么类型的值。如果设置后 $result["Users"]["is_login"] = true;您立即将其置于 if 条件中,该 if 条件应该触发。
  • 这将有助于在保存布尔值和 if 之间发布所有内容。

标签: php variables types


【解决方案1】:

没有演员表

if($result["Users"]["is_login"])

应该可以。 你可以尝试使用var_dump($result["Users"]["is_login"]); 来确保变量设置正确吗?

您可以使用isset (manual) 函数检查是否设置了变量。

您还可以找到here PHP 如何评估布尔值:

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).

【讨论】:

    【解决方案2】:

    在您的示例中没有进行强制转换。
    您的问题可能出在其他地方。

    您介意分享一段更完整的代码吗?

    【讨论】:

      【解决方案3】:

      试试:

      
      if((bool)$result["Users"]["is_login"] == true)
      {
          // do something
      }
      

      .

      并回复您遇到的一个问题:

      但是当我使用调试时 is_login 值是空白的。当我做这样的条件时:

      if($result["Users"]["is_login"])

      因为你的返回值是布尔值true,在PHP中它没有表示,因此显示为空(主要,如果值是布尔值false,那么你会看到一个@ 987654325@

      【讨论】:

      • 相反,当输出布尔值时,false 将为空白,true 将为 1
      猜你喜欢
      • 2013-11-22
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2010-12-12
      • 1970-01-01
      • 2020-09-21
      • 2012-12-08
      相关资源
      最近更新 更多