PHP Question: Printing A Boolean Value

8th April 2011

Question

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. $value = TRUE;
  2. if ($value === TRUE) {
  3. echo 'The value is TRUE';
  4. } else {
  5. echo 'The value is FALSE';
  6. }

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.

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

Comments

Permalink

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

Anonymous (Sat, 04/09/2011 - 01:41)

Permalink

42!

Anonymous (Sat, 04/09/2011 - 08:35)

Permalink

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

Mihai Baboi (Sat, 04/09/2011 - 15:35)

Add new comment

The content of this field is kept private and will not be shown publicly.