PHP filter_input_array() Function

PHP

PHP filter_input_array() - Filter Multiple Inputs

SEO Description: Learn PHP filter_input_array() function. Get and filter multiple external input variables efficiently.

In PHP, properly validating and sanitizing external input is essential to secure and robust applications. While functions like filter_input() handle a single variable, filter_input_array() lets you efficiently filter multiple inputs in one goβ€”ideal for forms or API data processing.

Prerequisites

  • Basic familiarity with PHP syntax and fundamentals.
  • Understanding of PHP filter extension and common input sources such as GET and POST.
  • PHP version 5.2.0 or higher (filter extension enabled, built-in since 5.2).

What is filter_input_array()?

The filter_input_array() function fetches multiple variables from a specified external variable source (like INPUT_GET, INPUT_POST) and filters them according to the rules you define in an array. It returns an associative array of filtered values or false on failure.


// Function signature:
array|false filter_input_array ( int $type , array|int|null $definition = null , bool $add_empty = true )
  

Parameters:

  • $type: One of the PHP input types, e.g., INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
  • $definition: An associative array specifying variable names and their filter rules, or a single filter constant applies to all.
  • $add_empty: Optional boolean. When true (default), keys not found in input will be set to null. If false, only variables present are returned.

Return value: An associative array mapping variable names to filtered values, or false on failure.

Setup Steps

  1. Ensure your PHP environment is version 5.2 or later with the filter extension enabled (usually enabled by default).
  2. Create a PHP script to receive external input through GET or POST.
  3. Define your validation and sanitization rules as an array.
  4. Use filter_input_array() to fetch and filter these inputs.

Practical Examples

Example 1: Filtering Multiple GET Inputs

Imagine a URL query string with parameters: ?name=JohnDoe&age=27&newsletter=yes. We want to filter them properly.


// Define filters:
$filters = [
    'name'      => FILTER_SANITIZE_STRING,
    'age'       => [
        'filter' => FILTER_VALIDATE_INT,
        'options' => ['min_range' => 18, 'max_range' => 120]
    ],
    'newsletter'=> FILTER_VALIDATE_BOOLEAN,
];

// Fetch and filter GET inputs
$inputs = filter_input_array(INPUT_GET, $filters);

if ($inputs === false) {
    echo "Failed to retrieve inputs.";
} else {
    var_dump($inputs);
}
/*
Output example:
array(3) {
  ["name"]=>
  string(7) "JohnDoe"
  ["age"]=>
  int(27)
  ["newsletter"]=>
  bool(true)
}
*/
  

Example 2: Using filter_input_array() to Filter POST Data with Defaults

When dealing with form submission via POST, you may want to set defaults if inputs are missing.


// Filters with default fallback and flags:
$filters = [
    'username' => FILTER_SANITIZE_STRING,
    'email'    => FILTER_VALIDATE_EMAIL,
    'subscribe'=> [
        'filter' => FILTER_VALIDATE_BOOLEAN,
        'flags'  => FILTER_NULL_ON_FAILURE
    ],
];

// Filter POST data, do not add empty keys:
$filtered_post = filter_input_array(INPUT_POST, $filters, false);

if ($filtered_post) {
    print_r($filtered_post);
} else {
    echo "No valid POST data found.";
}
  

Example 3: Applying Same Filter to All Inputs

If you want to sanitize all incoming GET request inputs using the same filter:


// Sanitize all GET variables as strings:
$all_get = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);

print_r($all_get);
  

Best Practices

  • Always specify filters for each expected input rather than a blanket filter, to avoid unexpected results.
  • Use FILTER_VALIDATE_* filters for strict validation where possible.
  • Use FILTER_SANITIZE_* filters for light sanitization but combine with validation when needed.
  • Leverage options and flags such as FILTER_NULL_ON_FAILURE to differentiate between invalid and missing inputs.
  • When using $add_empty = false, handle missing parameters to avoid undefined keys.
  • Always check the return value β€” it can be false, or values can be false or null, so test carefully.

Common Mistakes

  • Passing incorrect input type constants (e.g., using INPUT_REQUEST, which is not supported).
  • Assuming filter_input_array() returns filtered inputs with unchanged keys even if inputs don't exist.
  • Failing to handle the case when filter_input_array() returns false, leading to runtime errors.
  • Using FILTER_SANITIZE_STRING without understanding it is deprecated as of PHP 8.1; consider alternatives like FILTER_UNSAFE_RAW with flags or manual sanitation.
  • Neglecting to provide an appropriate filter definition array and relying on PHP defaults or applying the same filter to all inputs blindly.

Interview Questions

Junior Level

  1. Q: What is the purpose of the filter_input_array() function in PHP?
    A: It is used to get and filter multiple external input variables from sources like GET or POST in a single call.
  2. Q: Which input types can filter_input_array() handle?
    A: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, and INPUT_ENV.
  3. Q: What data type does filter_input_array() return on success?
    A: An associative array of filtered input values.
  4. Q: What does setting the $add_empty parameter to false do?
    A: It prevents keys of missing variables from being added to the returned array.
  5. Q: Can filter_input_array() filter both GET and POST data?
    A: Yes, depending on the $type argument provided.

Mid Level

  1. Q: How do you specify different filters for multiple inputs using filter_input_array()?
    A: By passing an associative array where keys are input names and values are filter constants or arrays with filter and options.
  2. Q: What happens if an input fails its validation filter in filter_input_array()?
    A: Its value will be set to false in the returned array.
  3. Q: How can you differentiate between an absent input and one that failed validation?
    A: Using the FILTER_NULL_ON_FAILURE flag will return null if input is absent, and false if it fails validation.
  4. Q: Why is it important to check if filter_input_array() returns false?
    A: Because it indicates failure to retrieve variables or incorrect parameters, and prevents errors in subsequent code.
  5. Q: Can filter_input_array() be used for bulk sanitization? Give an example.
    A: Yes, e.g., to sanitize all GET parameters as strings: filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);

Senior Level

  1. Q: Discuss the implications of using FILTER_SANITIZE_STRING with filter_input_array() in PHP 8.1 and above.
    A: FILTER_SANITIZE_STRING is deprecated; alternatives should be used, such as FILTER_UNSAFE_RAW with flags or custom sanitization to avoid security issues.
  2. Q: How would you handle complex nested input arrays using filter_input_array() given its limitations?
    A: Since filter_input_array() does not support filtering nested arrays directly, you should handle nested inputs manually or sanitize recursively after fetching raw input.
  3. Q: Explain how you would combine filter_input_array() with custom validation logic.
    A: Use filter_input_array() for initial filtering/validation, then pass the sanitized results to custom logic to check business-specific rules beyond standard filters.
  4. Q: Describe a scenario where use of $add_empty = false is preferred.
    A: When only explicitly submitted inputs are needed and missing keys should not pollute the result array or when unset keys require special handling.
  5. Q: How does filter_input_array() affect performance when filtering numerous inputs, and how would you optimize its use?
    A: It is efficient for batch filtering multiple variables in one call versus multiple calls to filter_input(). To optimize, define precise filters and limit filtering to expected inputs only.

Frequently Asked Questions (FAQ)

Q1: What is the difference between filter_input() and filter_input_array()?

filter_input() filters a single external variable, whereas filter_input_array() filters multiple inputs at once via an array of filters.

Q2: What input sources can filter_input_array() read from?

It can read from INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, and INPUT_ENV.

Q3: What does FILTER_VALIDATE_BOOLEAN return when filtering inputs?

It returns true or false based on typical boolean values, or null if the FILTER_NULL_ON_FAILURE flag is set and the value is not a recognizable boolean.

Q4: Can I use filter_input_array() to filter uploaded files data?

No. filter_input_array() does not filter the $_FILES array; uploaded files require separate handling.

Q5: What happens if you omit the filter definition in filter_input_array()?

If you omit the second argument, all variables will be fetched with FILTER_DEFAULT, which is equivalent to FILTER_UNSAFE_RAW without any sanitization or filtering.

Conclusion

filter_input_array() is a powerful and convenient PHP function designed to filter multiple external inputs efficiently. Using it correctly improves input validation, reduces repetitive code, and strengthens security when handling GET, POST, and other data sources. By defining appropriate filters and handling the results carefully, developers can build more secure and reliable applications with less hassle.

When used together with best practices and awareness of its nuances β€” like handling deprecated filters and managing missing inputs β€” filter_input_array() is an essential tool in any PHP developer's input validation toolkit.