gpt4 book ai didi

php - 将 php 函数返回值转换为 true/false

转载 作者:可可西里 更新时间:2023-10-31 23:38:12 25 4
gpt4 key购买 nike

我首先提到了这个this ,但它并没有解决我的问题。

我有这样的事情:

  $message .=   "\n\tWhether $testOutputDir is a directory:" . (!!is_dir($testOutputDir))
. "\n\tWhether $outputDir is a directory:" . is_dir($outputDir)
. "\n\tWhether $outputDir is readabale:" . is_readable($outputDir)
....

我只想打印如下内容:

       Whether /a is a directory: true
Whether /b is a directory: true

但是打印如下:

       Whether /a is a directory: 1
Whether /b is a directory: 1

有什么解决这个问题的建议吗?

编辑:

我可以检查 func == 1 吗?真:假。但我期待一个简单的转换或类似的转换。

最佳答案

在 PHP 中,当 bool 值转换为字符串时,您会得到 '1'(对于 true)和 ''(空字符串,表示 false)。如果您不希望这样做,则必须将 bool 值显式转换为字符串。

没有 Actor 可以让你得到你想要的结果。解决问题的一种方法是将您的值传递给此函数:

function stringForBool($bool) {
return ($bool ? 'true' : 'false');
}

//use like:
echo stringForBool(isReadable($outputDir));

您也可以直接在您的代码中内联此函数,而不是调用它,但如果您多次使用它,那将变得非常重复。

其他答案建议使用 json_encode()。虽然这确实有效(如果您传入一个 bool 值),但如果您传入的内容不完全是 truefalse,您将无法获得预期的输出。当然,您可以调用 json_encode((bool)$yourValue),这将为您提供您想要的内容,但(在我看来)它更神奇,更不明确。

关于php - 将 php 函数返回值转换为 true/false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com