note 74093 deleted from function.empty by danbrown
| From: | danbrown@php.net | Date: | Fri, 28 Nov 2008 22:07:46 +0000 |
| Subject: | note 74093 deleted from function.empty by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-147303@lists.php.net to get a copy of this message | ||
Note Submitter: M
----
The empty() function is not exactly useful.... it defines both "0" and 0 (the numerical
version) as empty. That's not really true is it!
Consider a user updating a record and setting a value to 0. When the form is posted and empty() is
used to check for empty values it will return true. If you are testing for a mandatory field this
will fail... even though the field has a value.
The following checks if a field is "really" empty, and includes as many test cases as I
could think of.
<?php
function isempty($var) {
if (((is_null($var) || rtrim($var) == "") && $var !== false) || (is_array($var)
&& empty($var))) {
echo "yes<br />";
} else {
echo "no<br />";
}
}
echo "1. unset variable - yes - ";
isempty($unset);
echo "2. empty string - yes - ";
$var = "";
isempty($var);
echo "3. zero string - no - ";
$var = "0";
isempty($var);
echo "4. zero number - no - ";
$var = 0;
isempty($var);
echo "5. null string - yes - ";
$var = null;
isempty($var);
echo "6. single space - yes - ";
$var = " ";
isempty($var);
echo "7. several space - yes - ";
$var = " ";
isempty($var);
echo "8. true - no - ";
$var = true;
isempty($var);
echo "9. false - no - ";
$var = false;
isempty($var);
echo "10. empty array - yes - ";
$var = array();
isempty($var);
?>
The output from this should be...
1. unset variable - yes - yes
2. empty string - yes - yes
3. zero string - no - no
4. zero number - no - no
5. null string - yes - yes
6. single space - yes - yes
7. several space - yes - yes
8. true - no - no
9. false - no - no
10. empty array - yes - yes
Regards,
M