44

I am new to PHP. I am implementing a script and I am puzzled by the following:

$local_rate_filename = $_SERVER['DOCUMENT_ROOT']."/ghjr324l.txt";
$local_rates_file_exists = file_exists($local_rate_filename);

echo $local_rates_file_exists."<br>";

This piece of code displays an empty string, rather than 0 or 1 (or true or false). Why? Documentation seems to indicate that a boolean value is always 0 or 1. What is the logic behind this?

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

4 Answers4

54

Be careful when you convert back and forth with boolean, the manual says:

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.

So you need to do a:

echo (int)$local_rates_file_exists."<br>";
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
dynamic
  • 46,985
  • 55
  • 154
  • 231
23

About converting a boolean to a string, the manual actually says:

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.

A boolean can always be represented as a 1 or a 0, but that's not what you get when you convert it to a string.

If you want it to be represented as an integer, cast it to one:

$intVar = (int) $boolVar;
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
  • 23
    +1 "This allows conversion back and forth between boolean and string values." That would have been also the case if FALSE were converted instead to "0". But, I guess, that would be too consistent, and PHP always tries hard to surprise the programmer. – leonbloy Jan 10 '13 at 15:02
  • 4
    It is possible to write a web application in PHP, but it is also possible to hike a mile in a foot of snow in your socks. – BaseZen Feb 18 '19 at 17:23
1

The results come from the fact that php implicitly converts bool values to strings if used like in your example. (string)false gives an empty string and (string)true gives '1'. That is consistent with the fact that '' == false and '1' == true.

clime
  • 8,695
  • 10
  • 61
  • 82
  • No, it does not from what I can see. No
    (line break) is printed.
    – Jérôme Verstrynge Jan 28 '12 at 01:06
  • Run php -a in console. Then do echo false."
    "; and echo true."
    ";. Btw. sry that I edited the post so that your comment has lost the context. I had done it before I have read this.
    – clime Jan 28 '12 at 01:10
0

If you wanna check if the file exists when your are not sure of the return type is true/false or 0/1 you could use ===.

if($local_rates_file_exists === true)
{
   echo "the file exists";
}
else
{
   echo "the doesnt file exists";
}
Bjørn Thomsen
  • 348
  • 2
  • 9