note 88635 deleted from function.is-bool by cmb
| From: | cmb@php.net | Date: | Fri, 01 Feb 2019 14:40:41 +0000 |
| Subject: | note 88635 deleted from function.is-bool by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210172@lists.php.net to get a copy of this message | ||
Note Submitter: sam+nospam at samuellevy dot com
----
Just another little function which doesn't exist yet, but I find mighty useful, especially when
working with AJAX and APIs.
<?php
/** Checks a variable to see if it should be considered a boolean true or false.
* Also takes into account some text-based representations of true of false,
* such as 'false','N','yes','on','off', etc.
* @author Samuel Levy <sam+nospam@samuellevy.com>
* @param mixed $in The variable to check
* @param bool $strict If set to false, consider everything that is not false to
* be true.
* @return bool The boolean equivalent or null
*/
function boolval($in, $strict=false) {
$out = null;
// if not strict, we only have to check if something is false
if (in_array($in,array('false', 'False', 'FALSE', 'no',
'No', 'n', 'N', '0', 'off',
'Off', 'OFF', false, 0, null), true)) {
$out = false;
} else if ($strict) {
// if strict, check the equivalent true values
if (in_array($in,array('true', 'True', 'TRUE',
'yes', 'Yes', 'y', 'Y', '1',
'on', 'On', 'ON', true, 1), true)) {
$out = true;
}
} else {
// not strict? let the regular php bool check figure it out (will
// largely default to true)
$out = ($in?true:false);
}
return $out;
}
?>
It may be pretty inefficient, but it does the job.