Reputation: 22964
I first referred to this this, but it did not solve my problem.
I am having something like:
$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)
....
I just want to print something as follows:
Whether /a is a directory: true
Whether /b is a directory: true
But it prints as follows:
Whether /a is a directory: 1
Whether /b is a directory: 1
Any suggestions to solve this?
EDIT:
I could check func == 1 ? TRUE : FALSE
. But I am expecting a simple cast or similar.
Upvotes: 4
Views: 643
Reputation: 5668
In PHP, when a boolean value is converted to a string, you get '1'
(for true
) and ''
(empty string, for false
). If you want otherwise, you're going to have to explicitly convert the boolean value to a string.
There is no cast that will get you the result you want. One way to solve your problem would be to pass your value into this function:
function stringForBool($bool) {
return ($bool ? 'true' : 'false');
}
//use like:
echo stringForBool(isReadable($outputDir));
You could also inline this function directly in your code, rather than calling it, but if you're using it more than a few times, that would become awfully repetitive.
Other answers suggest using json_encode()
. While that certainly works (if you pass in a boolean value), you will not get the expected output if you pass in something that isn't exactly true
or false
. You can, of course, call json_encode((bool)$yourValue)
, that that will give you what you want, but (in my opinion) it's a little more magical and a little less explicit.
Upvotes: 1
Reputation: 38502
This may work,
echo json_encode(true); // string "true"
echo json_encode(false); // string "false"
So,
$message .= "\n\tWhether $testOutputDir is a directory:" . json_encode(!!is_dir($testOutputDir))
. "\n\tWhether $outputDir is a directory:" . json_encode(is_dir($outputDir))
. "\n\tWhether $outputDir is readabale:" . json_encode(is_readable($outputDir))
Upvotes: 0
Reputation: 24699
You'd be stuck doing this:
is_dir($outputDir) ? 'true' : 'false'
Converting a bool
to a string
in PHP always converts it to ""
or "1"
.
Now, this is a bit of a hack, but you can actually just use json_encode()
:
php > var_dump(json_encode(true));
string(4) "true"
Upvotes: 0