215

The following code doesn't print out anything:

$bool_val = (bool)false;
echo $bool_val;

But the following code prints 1:

$bool_val = (bool)true;
echo $bool_val;

Is there a better way to print 0 or false when $bool_val is false than adding an if statement?

Jon Surrell
  • 9,444
  • 8
  • 48
  • 54
Anonymous1
  • 3,877
  • 3
  • 28
  • 42

14 Answers14

298
echo $bool_val ? 'true' : 'false';

Or if you only want output when it's false:

echo !$bool_val ? 'false' : '';
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 126
    It's confusing, sprawling & unhelpful without any apparent benefit. I've been programming for 20+ years and *never* have I wanted 'false' to auto-convert to blank.. null many times, but never 'false'. My Java/Spring/Hibernate development is so so so much cleaner & stronger than even modest PHP systems. **I could find plenty of people who were confused..** http://stackoverflow.com/questions/9042002/php-printed-boolean-value-is-empty-why **but I couldn't find any reference as to a real _reason_ for this design "feature".** – Thomas W Jul 16 '13 at 10:04
  • 8
    I really wanted to argue why (string)FALSE == "" is a good idea based on this bit from PHP's documentation: "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." but I tested it out, and (bool)"0" also evaluates to FALSE, so... I dunno. I love PHP, but I can't deny that that's kinda' weird >_> – Ben Dec 12 '13 at 23:02
  • 13
    It isn't weird that `FALSE == ''`. It's perfectly valid and a part of other languages, including javascript. What's weird is FALSE defaults to an empty string. It should default to 0. Always. Especially since TRUE will always default to 1. This breaks a cardinal rule of programming. Keep your code consistent. This is clearly a bug. – Literphor Nov 09 '14 at 08:11
  • 3
    While this is the simplest way to do this, running an array through print_r that contains boolean values, those values will show blank unless you previously run the array through a loop that swaps them out, so if you're just trying to debug or log, it becomes a giant pain in the neck to see if the values are actually true or false or something else that looks blank. – Dave Heq Oct 21 '16 at 19:16
  • 2
    @Ben although `!! '0'` evaluates to `false` in PHP, it's `true` in JS. `!! ""` is false in JS and PHP. – Charlie Dec 15 '16 at 02:51
84

This is the easiest way to do this:

$text = var_export($bool_value,true);
echo $text;

or

var_export($bool_value)

If the second argument is not true, it will output the result directly.

Saad
  • 13,269
  • 1
  • 19
  • 12
  • 1
    Thank you. There is no need to make a stupid language even weirder. Even in php there are workarounds to make it sort of okay. – ThaJay Sep 14 '21 at 14:51
53

This will print out boolean value as it is, instead of 1/0.

    $bool = false;

    echo json_encode($bool);   //false
serdar.sanri
  • 2,217
  • 1
  • 17
  • 21
34

No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".

Edit:

If you really wanted to, you could use an array:

$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false];
Avión
  • 7,963
  • 11
  • 64
  • 105
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
23

var_export provides the desired functionality.

This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.

var_export(true);    // true
var_export(false);   // false
var_export(1);       // 1
var_export(0);       // 0
var_export(null);    // NULL
var_export('true');  // 'true'   <-- note the quotes
var_export('false'); // 'false'

If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:

var_export((bool) true);   // true
var_export((bool) false);  // false
var_export((bool) 1);      // true
var_export((bool) 0);      // false
var_export((bool) '');     // false
var_export((bool) 'true'); // true
var_export((bool) null);   // false

// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0');     // false
Jon Surrell
  • 9,444
  • 8
  • 48
  • 54
23

Try converting your boolean to an integer?

 echo (int)$bool_val;
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
23

I like this one to print that out

var_dump ($var);
akond
  • 15,865
  • 4
  • 35
  • 55
6

The %b option of sprintf() will convert a boolean to an integer:

echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1

If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.

Each pattern will be replaced by the argument in order:

echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");
nuala
  • 2,681
  • 4
  • 30
  • 50
6
echo(var_export($var)); 

When $var is boolean variable, true or false will be printed out.

Maarkoize
  • 2,601
  • 2
  • 16
  • 34
mohamedeimo
  • 69
  • 1
  • 1
  • In my opinion, the best solution when exporting PHP variables in JavaScript ! – RPDeshaies Sep 30 '14 at 20:26
  • 4
    This is a bit misleading. `var_export` in this case will echo its result and return null, so var_export is outputting the `true || false`, and `echo` is echoing `null` (`''`). To return the output from `var_export`, you need to supply a second parameter as `true`. – Jon Surrell Dec 15 '14 at 11:14
  • @RPDeshaies if you want to export php variables to javascript `json_encode` is a better option. – andho Apr 12 '17 at 09:08
6

This gives 0 or 1:

intval($bool_val);

PHP Manual: intval function

David Oliver
  • 2,424
  • 1
  • 24
  • 37
3

You can use a ternary operator

echo false ? 'true' : 'false';
Aaron Hathaway
  • 4,280
  • 2
  • 19
  • 17
3

Your'e casting a boolean to boolean and expecting an integer to be displayed. It works for true but not false. Since you expect an integer:

echo (int)$bool_val;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
2

json_encode will do it out-of-the-box, but it's not pretty (indented, etc):

echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));

...gives...

{"whatever":true,"somethingelse":false}
Harry Pehkonen
  • 3,038
  • 2
  • 17
  • 19
0

You can try this if you want debug an array:

function debug_array($a){
    return array_map(function($v){
        return is_bool($v) ? ($v ? 'true' : 'false') : $v;
    }, $a);
}

To use it:

$arr = debug_array(['test' => true, 'id' => false]);
print_r($arr); // output Array ( [test] => true [id] => false )
Mohamad Hamouday
  • 2,070
  • 23
  • 20