测试字符串是否可以是布尔值PHP [英] Test if string could be boolean PHP

查看:67
本文介绍了测试字符串是否可以是布尔值PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从$ _GET获取一个字符串,我想测试它是否可以是布尔值,然后再将其用于mysql查询的一部分.有没有比以下更好的方法了?

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());
}

推荐答案

顺便说一下,有一种更干净的编写方式:

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.

这篇关于测试字符串是否可以是布尔值PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆