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
You can use default option to achieve this, If value not set then default value will get assign, example as given below
$options = array( 'options' => array('default'=> 0) );
$valid = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, $options);
filter_input() doesn't read from the _POST/_GET/_COOKIE/_SERVER/_ENV
$opened_staff['id'] = 0;
if($valid){
$opened_staff['id'] = $_GET['id'];
}
You can use some class to achieve this. [NOTE:- this is just an example]
class RequestFilter{
public static function get_filter_int($id){
$options = array( 'options' => array('default'=> 0) );
$valid = filter_input(INPUT_GET, $id, FILTER_VALIDATE_INT, $options);
if($valid){
return $_GET[$id]; // Value will return
}
return $valid; // Default will return
}
}
$opened_staff['id'] = RequestFilter::get_filter_int('id');
here will return value or default, here it is zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With