Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

3 things you probably didn't know about converting to Boolean values in PHP

Daniel Gheorghe Difficulty: 20 / 50 Tweet

For those of you who don't know, PHP is a "loosely typed" programming language. In other words, you don't need variable type declarations in PHP, because the type of a variable is determined by the interpreter depending on the context in which it is used.

As an example, in C++ when declaring a variable you have to write something like:

int myvariable=3;

The above code specifically tells the compiler that "myvariable" is an integer. In PHP on the other hand, all you need to do is assign the value to your variable and depending on the context, PHP will use the variable as an integer or whatever is needed.

<?php $myvariable = 1; ?>

For example, in the code below PHP will automatically cast the $a variable to a string so that it can concatenate it with the "Nr." string and the output will be: string(4) "Nr.1".

$a = 1;
var_dump("Nr." . $a);

The fact that PHP allows loose typing is an advantage in terms of how fast code can be written and how flexible your code can become, but it brings up a few pitfalls most of them related to type conversions. Because programmers most often convert values to Boolean this is what we're going to go through in this tutorial.

1. When converted to Boolean, a string variable that only contains an empty string or the string "0", will return FALSE. However, string "0.00" will return TRUE, while the float 0.00 will return FALSE (Weird isn't it ?).

var_dump((boolean)"0");  // bool(false)
var_dump((boolean)"0.0"); //bool(true)

2. The 0 integer converted to Boolean will have the value FALSE, but any other negative or positive integer will have the value TRUE.

var_dump((boolean)0);  // bool(false)
var_dump((boolean)-1); //bool(true)

3. An empty array will always return FALSE if converted to an integer, but as of PHP5, an object with no member properties will always return TRUE.

$a = array();
var_dump((boolean)$a);  // bool(false)
class anEmptyCLass { }
$a = new anEmptyCLass;
var_dump((boolean)$a);  // bool(true)