PHP Question: Printing A Boolean Value

Question

What will the following code print, and why?

echo TRUE;









 

Answer

The answer here is "1" because when we print out a boolean value in this way it is cast into a string, resulting in the integer value 1. If you try to do the same thing with a false value you will get no output (an empty string). This is important to remember as some items are lost in translation when printing out debug messages, even when using print_r().

The correct way to print out a boolean value is to use the var_dump() function. This will print out the correct value as well telling you what data type this is.

var_dump(TRUE); // bool(true)

You can also use an if statement to print out the value in the correct way.

$value = TRUE;
if ($value === TRUE) {
   echo 'The value is TRUE';
} else {
   echo 'The value is FALSE';
}

You can also print out TRUE as 1 and FALSE as 0, which is useful when inserting the value into a database. To do this you can use the sprintf() function to cast the boolean value into an integer.

print sprintf("%b", FALSE); // prints 0
print sprintf("%b", TRUE); // prints 1

Comments

I am not answering it because it will mean I am showing off!

Permalink

42!

Permalink

It prints 1. But the true problem comes with <code>echo FALSE</code> witch will print out nothing instead of 0 (zero). I've had some hassle with such code some time ago... :)

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.