A reminder to myself: Do not use “empty” in PHP in conjunction with POST requests…

I just stumbled over a silly bug in my code that took quite I while until I at last found the cause. I had several

if (isset($var) && (!empty($var)) { .... }

to process input that came via HTTP POST requests. This worked quite well, but there was one case where the code block was not executed even though the variable was set. In that case the content of the var was “0” (zero). I assumed that the function “empty” detects it a var is not filled with any value, but that was a wrong assumption as I had to see:

php > $a = "hello";
php > echo empty($a);

php > $a = "";
php > echo empty($a);

php > $a = 0;
php > echo empty($a);

Huh? What’s that? 0 == empty?? That’s not what I expected from a function with that name. But it turned out that that’s not a bug, but complies with the function description:

“Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. “

The second sentence is important: “…equals false”. In PHP a value of zero is interpreted as boolean false, so that’s the reason why this function does not behave the way we need here. I have no clue why they decided to make a function called “empty” to work that way, but I have to accept that anyway.

A decent code substitution for my use case could be:

if (isset($var) && ($var != "")) { .... }

Maybe I will remember this the next time… 😉

Categorized as Misc Tagged

Leave a comment

Your email address will not be published. Required fields are marked *