There's a few ways to do it. Firstly we could use PHP's in-built (boolean)
method, which casts a string value to a boolean:
$hopefullyBool = (boolean)$_GET['myVar'];
This would result in a boolean value of true
or false
depending on the value of the string in $_GET['myVar']
.
From v5.2.1 upwards, we can also use json_decode()
to ascertain the boolean value:
$hopefullyBool = json_decode($_GET['myVar]);
The json_decode()
method parses a JSON Object (which is a string) into a PHP variable, and takes type-casting into account. As a result, the string 'true'
from the URL param will be cast to the boolean true
.
You could use both of the above methods in tandem, using:
$hopefullyBool = (boolean)json_decode($_GET['myVar]);
To mitigate against uppercase characters being passed in the URL param (eg ?myVar=True
or ?myVar=FALSE
), you should use the strtolower()
method, which will convert a string to all lowercase letters:
$hopefullyBool = (boolean)json_decode(strtolower($_GET['myVar]));
Finally, we'll want to fall-back to false
if the parameter is not present in the URL's query string, otherwise PHP will throw an Undefined Index notice. To do this, we can use the isset()
method:
$hopefullyBool = false;
if ( isset($_GET['myVar']) ) {
$hopefullyBool = (boolean)json_decode(strtolower($_GET['myVar]));
}
To shorten this, you could initiate $hopefullyBool
using a conditional statement like so:
$hopefullyBool = isset($_GET['myVar']) && (boolean)json_decode(strtolower($_GET['myVar']));