note 124179 added to function.is-bool

From: Date: Sun, 08 Sep 2019 00:32:25 +0000
Subject: note 124179 added to function.is-bool
Groups: php.notes 
Request: Send a blank email to php-notes+get-212117@lists.php.net to get a copy of this message
The function Michael Smith published doesn't do the work as it should. To check if a variable is boolean is one thing, to evaluate if the value of a variable represents a boolean condition (true or false) is another. Here a simple function that checks the status of the received variable in regards to boolean equivalencies (case insensitive). <?php /** * Check "Booleanic" Conditions :) * * @param [mixed] $variable Can be anything (string, bol, integer, etc.) * @return [boolean] Returns TRUE for "1", "true", "on" and "yes" * Returns FALSE for "0", "false", "off" and "no" * Returns NULL otherwise. */ function is_enabled($variable) { if (!isset($variable)) return null; return filter_var($variable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); } ?> Of course, it is a simplistic approach, but for the majority of cases it will do the job right. And, just to put thing in the right perspective, here's a real function that does what Phill disclosed: <?php /** * Convert $variable to boolean (adapted from Phill answer) * * @param [mixed] $variable Can be anything * @return [boolean] Returns the booelan equivalent to $variable based on Zend Enegine interpretation */ function to_bool($variable) { return (bool)$variable; } ?> I hope it helps someone. Happy coding. ---- Server IP: 208.43.231.9 Probable Submitter: 82.199.157.54 (proxied: 67.149.168.182) ---- Manual Page -- http://php.net/manual/en/function.is-bool.php Edit -- https://master.php.net/note/edit/124179 Del: integrated -- https://master.php.net/note/delete/124179/integrated Del: useless -- https://master.php.net/note/delete/124179/useless Del: bad code -- https://master.php.net/note/delete/124179/bad+code Del: spam -- https://master.php.net/note/delete/124179/spam Del: non-english -- https://master.php.net/note/delete/124179/non-english Del: in docs -- https://master.php.net/note/delete/124179/in+docs Del: other reasons-- https://master.php.net/note/delete/124179 Reject -- https://master.php.net/note/reject/124179 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#212117) next »