php - filter_input - set to default value if GET key not set

10k views Asked by At

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.

2

There are 2 answers

2
Salman A On BEST ANSWER

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
2
Ashique C M On

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.