PHP has pretty flexible types. This is (usually) a good thing. It also has some rather handy functions to force types. Arguably the most useful of these is intval. When it comes to working with AJAX (in particular), or user generated input (in general), these functions are a godsend. The only one that seems to mysteriously be missing, though, is 'boolval'.
There's multiple solutions posted in the is_bool documentation comments, but here is my solution. I posted it on the comments section, but have refined it slightly since then. Hope this helps.
<?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 (if strict, and no exact equivalent) */ function boolval($in, $strict=false) { $out = null; $in = (is_string($in)?strtolower($in):$in); // if not strict, we only have to check if something is false if (in_array($in,array('false','no', 'n','0','off',false,0), true) || !$in) { $out = false; } else if ($strict) { // if strict, check the equivalent true values if (in_array($in,array('true','yes','y','1','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; } ?>
Comments
There is a easy way
I think there is a quite easier way to do this, but the result is different.
The values 0, null, "0" and false for $val will result in false.
Everything else i checked ("false", object, strings) is true then.
AJAX calls, etc.
Yes, that works fine for many situations, but when you're working with ajax calls, and libraries, etc. (specifically Sencha, which is what spawned this) a checkbox will often return "true" or "false", rather than true or false.
In that situation, just using the inbuilt bool checker doesn't have the desired result
This 'boolval' function is more akin to the 'parseint' functions that exist in other languages, in that it takes into account the 'truth value' of a number of strings.
Post new comment