note 93165 deleted from function.is-bool by googleguy

From: Date: Sat, 12 Jan 2013 09:50:55 +0000
Subject: note 93165 deleted from function.is-bool by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192972@lists.php.net to get a copy of this message
Note Submitter: kim at steinhaug dot com ---- 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 } } ?>

« previous php.notes (#192972) next »