PHP Question: Printing A Boolean Value
Published by philipnorton42 on Fri, 04/08/2011 - 12:33Question
What will the following code print, and why?
1 | 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.
1 | var_dump(TRUE); // bool(true) |
You can also use an if statement to print out the value in the correct way.
1 2 3 4 5 6 | $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.
Comments
I am not answering it
Anonymous (not verified) - Sat, 04/09/2011 - 02:41I am not answering it because it will mean I am showing off!
42!
Anonymous (not verified) - Sat, 04/09/2011 - 09:3542!
It prints 1. But the true
Mihai Baboi (not verified) - Sat, 04/09/2011 - 16:35It 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... :)
Add new comment