Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if string could be boolean PHP

Tags:

php

boolean

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());
}
like image 366
DexCurl Avatar asked Nov 25 '11 17:11

DexCurl


1 Answers

You can either use is_bool() or as suggested on php.net:

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

http://php.net/manual/en/function.is-bool.php

The latter one will accept strings like "on" and "yes" as true as well.

like image 189
zrvan Avatar answered Oct 12 '22 23:10

zrvan