Tools Blog Learn Quizzes Smile API Log In / Sign Up
Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated our privacy policy to let you know that we use cookies to personalise content and ads. We also use cookies to analyse our traffic and we share information about your use of our site and application with our advertising and analytics partners. By using this website or our application you agree to our use of cookies. Learn more about the way this website uses cookies or remove this message.

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

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".

<?php 
$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 ?).

<?php 
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.

<?php 
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.

<?php 
$a = array();
var_dump((boolean)$a);  // bool(false)
class anEmptyCLass { }
$a = new anEmptyCLass;
var_dump($a);
var_dump((boolean)$a);  // bool(true)
?>
comments powered by Disqus