Home » Php » php – returning true outputs 1 but returning false outputs nothing

php – returning true outputs 1 but returning false outputs nothing

Posted by: admin July 12, 2020 Leave a comment

Questions:

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;
}
How to&Answers:

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.

Answer:

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);