note 93165 added to function.is-bool

From: Date: Wed, 26 Aug 2009 17:48:54 +0000
Subject: note 93165 added to function.is-bool
Groups: php.notes 
Request: Send a blank email to php-notes+get-159905@lists.php.net to get a copy of this message
Seems this is a most wanted function, so here is my version of it. I have been using this one for several years no and it works perfect for my needs. I have added "sloppy" human logic to it, and you could easily extend to your flavour. Like in norway some would use "ja" and "nei" instead of "yes" and "no". <?php /** * Checks a variable if it is true or false, humanlike. * We account for values as 'on', '1', '' and so on. * Finally, for some reare occurencies we account with * crazy logic to fit some arrays and objects. * * @author Kim Steinhaug, <kim@steinhaug.com> * @param mixed $var, the variable to check * * Example: * $test = 'true'; * if(_bool($test)){ echo 'true'; } else { echo 'false'; } */ function _bool($var){ if(is_bool($var)){ return $var; } else if($var === NULL || $var === 'NULL' || $var === 'null'){ return false; } else if(is_string($var)){ $var = trim($var); if($var=='false'){ return false; } else if($var=='true'){ return true; } else if($var=='no'){ return false; } else if($var=='yes'){ return true; } else if($var=='off'){ return false; } else if($var=='on'){ return true; } else if($var==''){ return false; } else if(ctype_digit($var)){ if((int) $var) return true; else return false; } else { return true; } } else if(ctype_digit((string) $var)){ if((int) $var) return true; else return false; } else if(is_array($var)){ if(count($var)) return true; else return false; } else if(is_object($var)){ return true;// No reason to (bool) an object, we assume OK for crazy logic } else { return true;// Whatever came though must be something, OK for crazy logic } } ?> ---- Server IP: 128.39.198.38 Probable Submitter: 193.91.145.178 ---- Manual Page -- http://www.php.net/manual/en/function.is-bool.php Edit -- https://master.php.net/note/edit/93165 Del: integrated -- https://master.php.net/note/delete/93165/integrated Del: useless -- https://master.php.net/note/delete/93165/useless Del: bad code -- https://master.php.net/note/delete/93165/bad+code Del: spam -- https://master.php.net/note/delete/93165/spam Del: non-english -- https://master.php.net/note/delete/93165/non-english Del: in docs -- https://master.php.net/note/delete/93165/in+docs Del: other reasons-- https://master.php.net/note/delete/93165 Reject -- https://master.php.net/note/reject/93165 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#159905) next »