note 77617 added to function.empty

From: Date: Wed, 05 Sep 2007 22:57:18 +0000
Subject: note 77617 added to function.empty
Groups: php.notes 
Request: Send a blank email to php-notes+get-130230@lists.php.net to get a copy of this message
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function: <?php function check_not_empty($s, $include_whitespace = false) { if ($include_whitespace) { // make it so strings containing white space are treated as empty too $s = trim($s); } return (isset($s) && strlen($s)); // var is set and not an empty string '' } ?> Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }. If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1) If you want to check if a string IS empty then do: !check_not_empty($var). So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1)) no need to do if (isset() && !empty()) anymore =] ---- Server IP: 69.147.83.197 Probable Submitter: 71.165.163.175 ---- Manual Page -- http://www.php.net/manual/en/function.empty.php Edit -- https://master.php.net/note/edit/77617 Del: integrated -- https://master.php.net/note/delete/77617/integrated Del: useless -- https://master.php.net/note/delete/77617/useless Del: bad code -- https://master.php.net/note/delete/77617/bad+code Del: spam -- https://master.php.net/note/delete/77617/spam Del: non-english -- https://master.php.net/note/delete/77617/non-english Del: in docs -- https://master.php.net/note/delete/77617/in+docs Del: other reasons-- https://master.php.net/note/delete/77617 Reject -- https://master.php.net/note/reject/77617 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#130230) next »