15

I'm getting a string from a $_GET and I want to test if it could be a boolean, before I use it for a part of a mysql query. Is there a better way of doing it than:

function checkBool($string){
    $string = strtolower($string);
    if ($string == "true" || $string == "false" || 
        $string == "1" || $string == "0"){
        return true;
    }
    else {
        return false;
    }
}

if (checkBool($_GET['male'])){
    $result = mysql_query(
        "SELECT * FROM my_table " .
        "WHERE male='".$_GET['male']."'") or die(mysql_error());
}
8
  • This won't work anyway. What is your column type for male? The MySQL boolean type is really just a tinyint(1) so if it's that then you should only check for 1s or 0s. If you're using char/varchar and have previously set it to "true" then comparing it with "yes" or "1" will still not match. Commented Nov 25, 2011 at 18:01
  • point taken for checking yes and no, edited my snippet accordingly. Column type is indeed tinyint(1)! so true, false, 1 and 0 is what I need to check for Commented Nov 25, 2011 at 18:12
  • @DexCurl, This doesn't really change anything. You'll still have to use your own function, rewrited as I answered below. Commented Nov 25, 2011 at 18:16
  • Checking for string equivalency won't work, though. Your SQL puts $_GET['male'] inside quote marks, so if $_GET['male'] was "true" you'd get SELECT * FROM my_table WHERE male='true'. This will actually return rows where male=0 because MySQL tries to convert the STRING "true" to a number but can't so it gives it the value 0. Take out the single quotes and it works as expected. Commented Nov 25, 2011 at 18:17
  • @daiscog, I believe you have NOT got the point of the question. Commented Nov 25, 2011 at 18:19

9 Answers 9

22

You can use filter_var() with FILTER_VALIDATE_BOOLEAN flag, like

<?php
$myString = "On";
$b = filter_var($myString, FILTER_VALIDATE_BOOLEAN);

However, it will return false for both false and incorrect values (which could be enough if all you need is to know whether input value is true. But if you need to truly validate the input value, consider using a function suggested in this answer to tell whether input value can be interpreted as boolean or not.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 i've been using php for years and i've never heard of this 'filter_var' function. cool! Although you have to be using php >= 5.2. thanks!
This doesn't really solve anything. "False" will return false in both is_bool() and $b.
Thanks for your answer zrvan! is_bool() doesn't work with strings as tested by var_dump(is_bool("true")); and filter_var works nicely to transform something into a boolean answer, but I needed something to check if string is a boolean first
is_bool() does work with strings: it always returns FALSE, which is the correct answer since strings are strings, not booleans ;-P
@Shoe see my answer for how filter_var() can be used to validate strings like "False" and be a viable solution to the problem.
11

There's, by the way, a cleaner way of writing it:

function checkBool($string){
    $string = strtolower($string);
    return (in_array($string, array("true", "false", "1", "0", "yes", "no"), true));
}

But yes. The one you wrote down is the only way.

6 Comments

Thanks for your Jeff, very nice way of doing it. Greatly appreciated!
This might look neater but involves more overhead for PHP. It has to create an array, store it in the heap, then call another function which does the comparison. The original function is more efficient.
@daiscog, seriously? How much does it cost more? 0.0000000000000000000000000001 nanosecond to perform 123456789 calls to that function? It will probably be near 3 minutes the time you'll need to figure out what that original function does.
Haha, yeah I have this discussion a lot. But I think the original function is pretty clear and I'm one of the "every clock cycle counts" brigade, I'm afraid. Old fashioned, I suppose, but I think it all adds up, especially in big applications.
See my answer to another question for a more flexible (yet more verbose) solution. DexCurl should really be using parameterized queries, anyway.
|
6

If you use the flag FILTER_NULL_ON_FAILURE, filter_var() will work nicely:

function CheckBool($Value) {
  return null !== filter_var($Value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}

Comments

2

No you got it, there isn't anything more you can do, you got all possible values that would normally be considered as true or false and you're doing the comparison the right way, you COULD optimize it using an IN_ARRAY maybe, but even so, i find this version quite good already.

Comments

2

Boolean variables contain true or false values. To test if string could be boolean, different approaches can be used:

  • is_bool($var): The function is_bool() checks whether a variable’s type is Boolean and returns true or false.

  • Comparison using “===” or ($var===true || $var===false): If you compare the variable with the operator “===” with true and false and if it is identical to one of the values, then it is a boolean value. Since the functionality of is_bool($var) is same, the function should be preferred.

  • Comparison using “==” or ($var == true || $var == false): If you use “==” as an operator instead, the test is more tolerant. For example, 0(integer) or “”(empty string) would also result in a Boolean value.

Comments

1

Your checkBool() is quite right, IMHO, though there's a problem with the resulting SQL code. You can use TRUE and FALSE, but you must be aware that they aren't strings:

The constants TRUE and FALSE evaluate to 1 and 0, respectively. The constant names can be written in any lettercase.

So where it says this:

"SELECT * FROM my_table WHERE male='".$_GET['male']."'"

... it should say this:

'SELECT * FROM my_table WHERE male='.$_GET['male']

It'd feel better if checkBool() was actually convertToBool() and you would feed your query with its result value rather than the original $_GET, but your code is not really wrong.

BTW, I'm assuming that you are using a BOOL column type. This is what the manual says:

These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true

Of course, it's up to you whether to use BOOL, ENUM, CHAR(1) or anything else, as well as whether to accept 33 as synonym for TRUE ;-)

Comments

0

For what it's worth, if you really wanted to accept "yes" or "no" as valid input from the user, then I'd do something like this:

function toBoolean($string){
    $string = strtolower($string);
    if ($string == "true" || $string == "1"|| $string == "yes" )
        return true;
    elseif ($string == "false" || $string == "0" || $string == "no")
        return false;
    else
        throw new Exception("You did not submit a valid value, you naughty boy");
}

try {
    $query = "SELECT * FROM my_table WHERE male=" . (toBoolean($_GET['male']) ? "1" : "0" );
    $result = mysql_query($query) or die(mysql_error());
} catch (Exception $e) {
    // handle bad user input here
}

1 Comment

What about fetching all this instructions... "every clock cycle counts" brigade... ahah
0

Sometimes API or other sources convert bool value (true, false) to string, you can check bool status by this code in PHP.

$boolFlag="false";

$convetToBool = json_decode($boolFlag);

if(!empty($convetToBool)){
  //do any work in true condtion;
}

1 Comment

Using json_decode() is too much overhead for a simple task as this, don't you think so ?
-1

You can use is_bool to test your string:

if(is_bool($val)){
  // is boolean
}else{
  // not a boolean
}

1 Comment

is_bool will return true only if $val is "pure" true or false, but it will return false for "true" and "false" strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.