Passing a boolean through PHP GET

2019-02-21 19:19发布

Pretty simple question here, not sure the answer though. Can I pass a boolean variable through get? For example:

http://example.com/foo.php?myVar=true

then I have

$hopefullyBool = $_GET['myVar'];

Is $hopefullyBool a boolean or a string? My hypothesis is that it's a string but can someone let me know? Thanks

标签: php get boolean
3条回答
混吃等死
2楼-- · 2019-02-21 20:01

All GET parameters will be strings in PHP. To get the type boolean, pass as something that evaluates to true or false like 0 or 1, then use:

$hopefullyBool = (bool)$_GET['myVar'];

If you want to pass string true or false then:

$hopefullyBool = $_GET['myVar'] == 'true' ? true : false;

Or even better:

Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

$hopefullyBool = filter_var($_GET['myVar'], FILTER_VALIDATE_BOOLEAN);
查看更多
仙女界的扛把子
3楼-- · 2019-02-21 20:06

It would be passed as a string. While you can convert it using the bool cast, it is recommended to not do so in some cases.

You would be better off doing if myVar == "True"

Be cautious:

>>> bool("foo")
True
>>> bool("")
False

Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-21 20:14

If you want to avoid an if statement:

filter_var('true', FILTER_VALIDATE_BOOLEAN);  
//bool(true)

filter_var('false', FILTER_VALIDATE_BOOLEAN); 
//bool(false)
查看更多
登录 后发表回答