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
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 string 0
or 1
:
http://example.com/foo.php?myVar=0
http://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.