I'd like to have a clean, elegant way to set a variable to a GET parameter if said parameter is set (and numeric), and to 0 (or some other default) if it's not set.
Right now I have:
if (($get_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))) {
$opened_staff['id'] = $get_id;
// some database queries etc.
} else { $opened_staff['id'] = 0; }
I tried using a callback function that returns 0 if the value is null or not numeric, but if the GET parameter 'id' isn't set, the callback won't even be called - it just sets $get_id
to null.
Not a big deal to include the else statement, just thought I might be missing out on some functionality of filter_input
.
The filter_input
function accepts an options
parameter. Each filter accepts different options. For example, the FILTER_VALIDATE_INT
filter can accept default
, min_range
and max_range
options as described here.
$get_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, array("options" => array(
"default" => 0,
"min_range" => 0
)));
var_dump($get_id);
// $get_id = 0 when id is not present in query string, not an integer or negative
// $get_id = <that integer> otherwise