www.retosphere.de

PHP empty()

Home
Projects
News
Links
GuestBook
Contact
Have you ever noticed that a variable containing 0 is empty?
That might even be intelligent, why should 0 not be empty? But PHP is so strange, I just do not know if or what the programmers of PHP smoked when creating PHP.

Table of contents:
1. Some examples
2. Work around problems
3. Annotations to empty() and the manual


   Here are a few examples:

 
<?php
$x 
0;
echo empty(
$x);
?>
Here the variable $x gets the value 0, empty($x) results true.
That's clear, it is just as defined: 0 is empty.
show me
 
 
<?php
$x 
"";
echo empty(
$x);
?>
Here the variable $x is an empty string, empty($x) results true.
That's clear, an empty string results empty.
show me
  
 
<?php
$x 
"0";
echo empty(
$x)." - ";
echo 
strlen($x);
?>
Here the variable $x is a string that is NOT empty but contains "0".
Still empty($x) results true.
This is getting strange. Why is a string of length 1 (strlen($x)=1) empty???
Just imagine the following situation:
You have a form where integer values can be entered, including the value 0. Forms are submitted as strings and you want to be able to result an error when nothing is entered. You cannot use empty() for this check, because entering the valid value 0 would be the same as entering nothing.
If anyone can explain, I would be glad.
Just to make it clear: other languages without strong typisation like PHP (such as Python result empty($x)=false!
show me
 
Now, why do we need empty()??
Most people simply use the negation:
 
<?php
$x 
0;
if (!
$x) echo "empty";
?>
You can see the problem when you change your PHP-configuration (in PHP.ini):
Set the Error_Level to: E_ALL (the standard is: E_ALL & ~E_NOTICE, which means, all errors but no Notices)

Then run this little script (right-click on "show me" and save it to your hard-disk).
You will get a warning: Variable $x not known. (or something similar).
This is because you use a variable that is not yet defined. The message is very useful because you get the information if you forgot something like the "global" declaration, a parameter is not passed or something alike....
show me
(Error level is set to "No Warnings", so you won't see the warning here...)
So, it might be useful NOT using the negation but using empty instead (it makes programming/debugging very much easier. And it would be even easier if there was a strict concept about the return values of functions and internal treatment of PHP variables...
 
 
  Finally, I would like to show you a work-around that was proposed in a contribution to the PHP-manual entry for empty():
This examples makes it possible to check form values and allow "0" as value.
 
<?php
if (!isset($form["x"]) || ($form["x"] == ""))
    echo 
"error in form";
?>


  Annotations to the PHP-empty() problem and the manual


Top
© retosphere.de
this page last updated: 28.11.2013
Top