note 109419 added to function.is-bool
| From: | MattKantor | Date: | Mon, 16 Jul 2012 02:16:10 +0000 |
| Subject: | note 109419 added to function.is-bool | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-189150@lists.php.net to get a copy of this message | ||
@ 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.
----
Server IP: 192.41.42.26
Probable Submitter: 76.102.54.31
----
Manual Page -- http://www.php.net/manual/en/function.is-bool.php
Edit -- https://master.php.net/note/edit/109419
Del: integrated -- https://master.php.net/note/delete/109419/integrated
Del: useless -- https://master.php.net/note/delete/109419/useless
Del: bad code -- https://master.php.net/note/delete/109419/bad+code
Del: spam -- https://master.php.net/note/delete/109419/spam
Del: non-english -- https://master.php.net/note/delete/109419/non-english
Del: in docs -- https://master.php.net/note/delete/109419/in+docs
Del: other reasons-- https://master.php.net/note/delete/109419
Reject -- https://master.php.net/note/reject/109419
Search -- https://master.php.net/manage/user-notes.php