Passing a boolean through PHP GET Passing a boolean through PHP GET php php

Passing a boolean through PHP GET


All GET parameters will be strings (or an array of strings) in PHP. Use filter_var (or filter_input) and FILTER_VALIDATE_BOOLEAN:

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

If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

$hopefullyBool = filter_var($_GET['myVar'], FILTER_VALIDATE_BOOLEAN);

For INPUT vars that can be arrays there is filter_var_array and filter_input_array.

Another way to get the type boolean, pass something that evaluates to true or false like 0 or 1:

http://example.com/foo.php?myVar=0http://example.com/foo.php?myVar=1

Then cast to boolean:

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

If you want to pass string true or false then another way:

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

But I would say that filter_var with FILTER_VALIDATE_BOOLEAN was meant for this.


If you want to avoid an if statement:

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


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.