dsideal2015 2013-10-09 15:54
浏览 49
已采纳

什么是将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?

  • 写回答

3条回答 默认 最新

  • dongzg2006 2013-10-09 15:58
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?