Function to convert strings to strict booleans in PHP

By: oscar  

Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes.

<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'), $_forceLowercase = true)
{
if (is_string($_val)) {
return (in_array(
($_forceLowercase?strtolower($_val):$_val)
, $_trueValues)
);
} else {
return (boolean) $_val;
}
}
?>




Archived Comments


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial