note 109419 deleted from function.is-bool by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:03:36 +0000 |
| Subject: | note 109419 deleted from function.is-bool by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189169@lists.php.net to get a copy of this message | ||
Note Submitter: Matt Kantor
----
@ kim at steinhaug dot com
I recently needed a "sloppy" boolean conversion function similar to yours. I felt a bit
uncomfortable using hard-coded truthy/falsy strings (after all, the list could go on forever), so I
wrote my own:
<?php
function loosely_cast_to_boolean($value) {
if(is_array($value) || $value instanceof Countable) {
return (boolean) count($value);
} else if(is_string($value) || is_object($value) && method_exists($value,
'__toString')) {
$value = (string) $value;
// see http://www.php.net/manual/en/filter.filters.validate.php#108218
$filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if(!is_null($filtered)) {
return $filtered;
} else {
// "none" gets special treatment to be consistent with ini file behavior.
// see documentation in php.ini for more information, in part it says:
// "An empty string can be denoted by simply not writing anything after
// the equal sign, or by using the None keyword".
if(strtolower($value) === 'none') {
$value = '';
}
return (boolean) $value;
}
} else {
return (boolean) $value;
}
}
?>
Note that for objects which are both countable and string-castable, this will favor the count over
the string value to determine truthiness. That is, if <?php $object instanceof Countable ?>
this will return <?php (boolean) count($object) ?> regardless of the value of <?php
(string) $object ?>.
You can see the behavior for the test data I used as well as the results for several other functions
(including your [kim's] version) here: http://codepad.viper-7.com/ErfNQ5 . It's kind of
hard to skim the results from that little iframe, so you can view the script output in a full page,
instead: http://codepad.viper-7.com/ErfNQ5/5.4.0 (this URL
is undocumented so it might not work forever). The line between what "ought to be true"
and what oughtn't is pretty arbitrary; the data I used is categorized based on my needs and
aesthetic preferences, yours may differ.