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
Answer
All GET parameters will be strings in PHP. Use filter_var
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);
Another way to get the type boolean, pass as something that evaluates to true
or false
like 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.
No comments:
Post a Comment