什么是将bool转换为文本值的最佳逻辑

I find myself writing code very similar to this regularly, in PHP and in C#

print isset($required) ? ($required ? "required" : "not required") : "not required";

Feels like I should be able to do something like this

print falseornull($required) ? "not required" : "required"

I could write a function to do this for me in PHP or C#, but I'm wondering if something already exists in either language? In C# I know there's string.IsNullOrEmpty to check for blank strings. Any equivalents for other types?

Just as a code simplifier... If you're not checking for $required to be equal to a particular value, this:

print isset($required) ? ($required ? "required" : "not required") : "not required"; 

should be the same as this:

print empty($required) ? "not required" : "required";

empty() does just what you're after: "Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist. [...] The following things are considered to be empty:

"" (an empty string)"

http://us1.php.net/empty

I guess the equivalent to C#'s string.IsNullOrEmpty is empty() in PHP. If the value is not set (NULL) or is set to false it will return true

// We'll set some variables in PHP
$variable1 = null;
$variable2 = 0;
$variable3 = false;

// Variable that doesn't exist, because we've commented it out
// $variable4 = 'something';

// When put into the function like so
print empty($variable1) ? true : false; // true
print empty($variable2) ? true : false; // false
print empty($variable3) ? true : false; // true
print empty($variable4) ? true : false; // true

Here's the docs for the function http://php.net/manual/en/function.empty.php

isset() is the opposite function

Just to add a C# alternative:

bool? b = .... ;
Console.WriteLine(b.GetValueOrDefault(false) ? "istrue" : "isnottrue");

Disclaimer, writing this without C# compiler at hand, but it should be GetValueOrDefault :)