returning true outputs 1 but returning false outputs nothing

℡╲_俬逩灬. 提交于 2020-01-12 16:47:04

问题


It's not very important but I was just curious to know the difference.

echo isA("A");  //outputs 1

echo isA("B");  //outputs nothing. why doesn't it output 0?  

Anybody can shed somelight on this matter? It does seem to me as a double standard when you look at it from the point of view that "true" outputs as "1" but "false"does not output "0".

Again, no big deal but I think there must be a reason for PHP to be designed like that. Knowing that may give some more insight into this beautiful language.

A true value will manifest itself as a visible 1, but a false value won't. So, tell me what's the advantage of this method?

example function I referred above;

function isA($input){
    if ( $input == "A" ):
        return true;
    else:
        return false;
    endif;
}

回答1:


A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting

If you want to print a boolean for debugging you can use var_dump or print_r.




回答2:


Because when false is casted to string it becomes '' -- empty string.

To see the difference use var_dump(); instead of echo

var_dump((string) true);
var_dump((string) false);


来源:https://stackoverflow.com/questions/9764231/returning-true-outputs-1-but-returning-false-outputs-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!