22

Possible Duplicate:
PHP - Get bool to echo false when false

Given the following test.php:

<?php

echo TRUE . "\n";    // prints "1\n"
echo FALSE . "\n";   // prints "\n"

?>

Why doesn't php -f test.php print TRUE or FALSE? More importantly, in the FALSE case, why doesn't it print anything?

Community
  • 1
  • 1
Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
  • 2
    `echo "TRUE";`, `echo "FALSE";` ? – Gntem Aug 12 '12 at 11:05
  • 1
    The latter is by design. It should output `1` for true though – Pekka Aug 12 '12 at 11:05
  • This is because `C` has no `boolean` but uses `0` for `FALSE` and everything else for `TRUE`. And PHP uses a lot of `C` concepts. Therefore you can use `if($foo)` in PHP which evaluates to `true` in every case when `$foo` is set, not empty and not `0` or `false`. – fdomig Aug 12 '12 at 11:16
  • 2
    @AgnelKurian `echo ($foo ? "TRUE" : "FALSE") ;` – Khaled.K May 24 '14 at 11:47

3 Answers3

39

From the manual:

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
23

Because false == '';

do this to print booleans:

$bool = false;
echo $bool ? 'true' : 'false';

or...

echo $bool ? 'yes' : 'no';
echo $bool ? '1' : '0';
Peter
  • 5,138
  • 5
  • 29
  • 38
8

Because boolean values when cast to a string are cast to 1 and an empty string respectively.

Supposedly this is to enable a transparent roundtrip between boolean -> string -> boolean.

deceze
  • 510,633
  • 85
  • 743
  • 889