note 74093 added to function.empty
| From: | M at osu1 dot php dot net | Date: | Sat, 24 Mar 2007 01:32:52 +0000 |
| Subject: | note 74093 added to function.empty | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124768@lists.php.net to get a copy of this message | ||
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
----
Server IP: 87.124.64.96
Probable Submitter: 82.32.129.242
----
Manual Page -- http://www.php.net/manual/en/function.empty.php
Edit -- https://master.php.net/note/edit/74093
Del: integrated -- https://master.php.net/note/delete/74093/integrated
Del: useless -- https://master.php.net/note/delete/74093/useless
Del: bad code -- https://master.php.net/note/delete/74093/bad+code
Del: spam -- https://master.php.net/note/delete/74093/spam
Del: non-english -- https://master.php.net/note/delete/74093/non-english
Del: in docs -- https://master.php.net/note/delete/74093/in+docs
Del: other reasons-- https://master.php.net/note/delete/74093
Reject -- https://master.php.net/note/reject/74093
Search -- https://master.php.net/manage/user-notes.php