PHP 打印的布尔值是空的,为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9042002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:01:42  来源:igfitidea点击:

PHP printed boolean value is empty, why?

phpbooleanecho

提问by Jér?me Verstrynge

I am new to PHP. I am implementing a script and I am puzzled by the following:

我是 PHP 新手。我正在实施一个脚本,但我对以下内容感到困惑:

$local_rate_filename = $_SERVER['DOCUMENT_ROOT']."/ghjr324l.txt";
$local_rates_file_exists = file_exists($local_rate_filename);

echo $local_rates_file_exists."<br>";

This piece of code displays an empty string, rather than 0 or 1 (or true or false). Why? Documentation seems to indicate that a boolean value is always 0 or 1. What is the logic behind this?

这段代码显示一个空字符串,而不是 0 或 1(或 true 或 false)。为什么?文档似乎表明布尔值始终为 0 或 1。这背后的逻辑是什么?

回答by dynamic

Be careful when you convert back and forth with boolean, the manual says:

使用布尔值来回转换时要小心,手册上说:

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

布尔值 TRUE 被转换为字符串“1”。Boolean FALSE 转换为 ""(空字符串)。这允许在布尔值和字符串值之间来回转换。

So you need to do a:

所以你需要做一个:

echo (int)$local_rates_file_exists."<br>";

回答by DaveRandom

About converting a boolean to a string, the manual actuallysays:

关于将布尔值转换为字符串,手册实际上

A boolean TRUEvalue is converted to the string "1". Boolean FALSEis converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

布尔值TRUE被转换为字符串“1”。Boolean FALSE转换为 ""(空字符串)。这允许在布尔值和字符串值之间来回转换。

A boolean can always be representedas a 1 or a 0, but that's not what you get when you convert it to a string.

布尔值始终可以表示为 1 或 0,但这不是将其转换为字符串时得到的结果。

If you want it to be represented as an integer, cast it to one:

如果您希望将其表示为整数,请将其强制转换为 1

$intVar = (int) $boolVar;

回答by clime

The results come from the fact that php implicitly converts bool values to strings if used like in your example. (string)falsegives an empty string and (string)truegives '1'. That is consistent with the fact that '' == falseand '1' == true.

结果来自这样一个事实,即如果在您的示例中使用,php 会隐式地将 bool 值转换为字符串。(string)false给出一个空字符串并(string)true给出'1'. 这是与事实相符'' == false'1' == true

回答by Bj?rn Thomsen

If you wanna check if the file exists when your are not sure of the return type is true/false or 0/1 you could use ===.

如果您想在不确定返回类型是真/假还是 0/1 时检查文件是否存在,可以使用 ===。

if($local_rates_file_exists === true)
{
   echo "the file exists";
}
else
{
   echo "the doesnt file exists";
}