Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP printed boolean value is empty, why?

Tags:

php

echo

boolean

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?

like image 422
Jérôme Verstrynge Avatar asked Jan 28 '12 00:01

Jérôme Verstrynge


People also ask

How do you print a boolean value?

The println(boolean) method of PrintStream Class in Java is used to print the specified boolean value on the stream and then break the line. This boolean value is taken as a parameter. Parameters: This method accepts a mandatory parameter booleanValue which is the boolean value to be written on the stream.

Can boolean be null PHP?

In PHP, the expression (FALSE != NULL) will always be FALSE , so code in your if block will never get executed. You could also use is_null() function.

Is bool true 1 or 0?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is empty string false in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


2 Answers

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>"; 
like image 102
dynamic Avatar answered Sep 25 '22 22:09

dynamic


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; 
like image 31
DaveRandom Avatar answered Sep 21 '22 22:09

DaveRandom