PHP 布尔值到字符串并进行修改 &一个条件

发布于 2024-09-18 11:04:41 字数 352 浏览 3 评论 0原文

echo 布尔值(true 或 false)时,PHP 将其转换为 1 并显示它。例如:

$x = true; echo $x; //displays: 1
$x = false; echo $x; //displays: <nothing>

我的问题:如果变量是布尔值,是否有一个 PHP 函数(如果不是如何编码的话)可以准确显示“true”或“false”(而不是 1 或什么都没有) 否则就按照 PHP 正常显示的方式显示。

When echoing a boolean (true or false), PHP converts it to 1 or <nothing> and displays it. e.g.:

$x = true; echo $x; //displays: 1
$x = false; echo $x; //displays: <nothing>

My Question: Is there a PHP function (if not how to code it) which can display exactly "true" or "false" (and not 1 or nothing), if a variable is a boolean otherwise just display as PHP would normally display it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

末蓝 2024-09-25 11:04:41

我一直在想这样做,但需要在没有函数的情况下内联它,所以我只是使用:

echo(is_bool($x) ? ($x ? "true":"false"):$x);

不是最容易阅读的,但可以完成工作!

I've just been looking to do this but needed to to it inline without a function so I just used :

echo(is_bool($x) ? ($x ? "true":"false"):$x);

Not the easiest to read but gets the job done!

我的痛♀有谁懂 2024-09-25 11:04:41

是的,它可以很容易地编码如下:

function var_to_str($in)
{
   if(is_bool($in))
   {
      if($in)
         return "true";
      else
         return "false";
   }
   else
      return $in;
}

//Test it now
echo var_to_str("this is string") . PHP_EOL;
echo var_to_str(123) . PHP_EOL;
echo var_to_str(true) . PHP_EOL;
echo var_to_str(false) . PHP_EOL;

输出:

this is string  
123  
true  
false  

Yes, it can be easily coded like this:

function var_to_str($in)
{
   if(is_bool($in))
   {
      if($in)
         return "true";
      else
         return "false";
   }
   else
      return $in;
}

//Test it now
echo var_to_str("this is string") . PHP_EOL;
echo var_to_str(123) . PHP_EOL;
echo var_to_str(true) . PHP_EOL;
echo var_to_str(false) . PHP_EOL;

This outputs:

this is string  
123  
true  
false  
时常饿 2024-09-25 11:04:41
str_replace(array(0, 1), array("No", "Yes"), str_pad(headers_sent(), 1, "0"))

我使用 headers_sent() 只是作为 BOOLEAN 变量。

str_replace(array(0, 1), array("No", "Yes"), str_pad(headers_sent(), 1, "0"))

I used headers_sent() just as a BOOLEAN variable.

一人独醉 2024-09-25 11:04:41

我遇到了这个问题,发现这个问题,答案并不完全是我需要的,所以我解决了这个:

array_pop(array_keys(array('FALSE' => false,'TRUE' => true), [bool] ))

来简单地获取 [bool] 的打印(回显)字符串值,将 [bool] 替换为您知道是 bool 的变量。

我认为这可能会帮助其他发现这个问题的人......

I had this issue, found this question and the answer was not quite what I needed, so I worked out this:

array_pop(array_keys(array('FALSE' => false,'TRUE' => true), [bool]))

to simply get a printed (echoed) string value for a [bool], replacing [bool] with a variable you know to be a bool.

Thought it might help others who find this question....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文