DEV Community

Nafis Nahiyan
Nafis Nahiyan

Posted on

🛑 Back to the Basics: WHY FALSE NEVER GETS PRINTED IN PHP ❓❓

âť—Boolean in all languages means a data type that can either be true or false. But in PHP, boolean has a mysterious behavior. Before getting into that, let's talk about true and false in PHP.

âť—In PHP, there are a few values that are by default false. They are:

  • false: The defined false value itself
  • null: The defined null value in PHP
  • 0 and -0: Positive and negative integer values of 0
  • 0.00 and -0.00: Positive and negative float values of 0
  • "": empty string
  • [ ]: Empty array

âť—Any other values except these are considered true in PHP. For example:

# This is an empty string value
$value = "";

# If we check it with is_bool()  
echo is_bool($value);
# we will get 1 or true 

Enter fullscreen mode Exit fullscreen mode

âť—On the other hand

# This is a string 
$value = "false";

# If we check it with is_bool()
echo is_bool($value);
# we will get no output or false
Enter fullscreen mode Exit fullscreen mode

âť—Now this brings us to the main question: WHY FALSE NEVER GETS PRINTED IN PHP?

Often, when we try to print a false value with echo or print, it prints nothing, no output on screen. But why?

❗For this, we have to understand the printing mechanism in PHP. While printing, both echo and print converts or typecasts everything into a string. That is why when we try to print an array with any of them, it gives us a conversion error because it can’t convert an array to a string. But for boolean values, they can do this.

âť—Both echo and print type casts a true boolean value into the string value "1" and a false boolean value into the string value "" which is an empty string and then prints the value. Let's test this with an example:

$test = true;
# Type casting the value into a string
$typeCasted = (string)$test;

# var_dump() displays the detailed information # about a variable 

var_dump($typeCasted);
# we get string(1) "" : which means 
# this is a string with 1 character
# and the value is "1" 

echo $test 
# this does the type casting 
# to convert into string
# and prints the value "1"

Enter fullscreen mode Exit fullscreen mode

On the other hand for false

$test = false;

# Type casting the value into string
$typeCasted = (string)$test;


var_dump($typeCasted);
# we get string(0) "" : which means 
# this is a string with 0 character
# and the value is empty string or ""

echo $test 
# echo does the type casting 
# to convert into string 
# and  prints the value ""

Enter fullscreen mode Exit fullscreen mode

âť—So this is why printing boolean true gives us a "1" string value, and printing false gives us a "" or empty string value. Thank you for reading.

Top comments (0)