Table of Content
The filter_var_array() appeared to make input validation simple and sanitization in PHP.
It handles multiple inputs with different filters was repetitive and error-prone.
Here is what we cover in this article:
- What
filter_var_arrayis in PHP and how it works. - How to validate form data with it.
- Validate email and URLs. Also, validate numbers with the filter_var_array function.
Let’s move on to its definition and how it works.
Understand the PHP filter_var_array
The filter_var_array() is a PHP function that filters multiple values in an array using specified validation and sanitization rules. It applies different filters to each element.
The syntax:
filter_var_array($array, $options, $add_empty)Here are the parameters:
$arrayrefers to the input array to filter. It should array type.$optionsparameter is an array of filters (key-value pairs) or a single filter for all values.$add_emptyis an optional ( defaulttrue). It controls whether missing keys should be added asnull.
It returns:
- The filtered array on success.
- A
falsevalue if filtering fails. - Returns
nullif the input is not an array.
Example 1: Validate Form Data with filter_var_array in PHP
Here is an example to validate form data:
$data = [
'name' => 'FlatCoding Username',
'email' => 'flatcodinguser@example.com',
'age' => '25'
];
// It defines validation rules
$filters = [
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL,
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18, 'max_range' => 100]
]
];
// Apply filters
$validatedData = filter_var_array($data, $filters);
// Check if validation passed
if ($validatedData['email'] === false || $validatedData['age'] === false) {
echo "Invalid input detected.";
} else {
print_r($validatedData);
}Output:
Array
(
[name] => FlatCoding Username
[email] => flatcodinguser@example.com
[age] => 25
)
How does it work?
FILTER_SANITIZE_STRINGremoves unwanted characters fromname.FILTER_VALIDATE_EMAILensuresemailis valid.FILTER_VALIDATE_INTchecks ifageis a number between 18 and 100.
This method ensures safe and validated user input.
Example 2: Validate Email, URLs, and Numbers with filter_var_array in PHP
This example shows you how to validate emails, URLs, and numbers:
// Sample input data (usually from $_POST or $_GET)
$data = [
'email' => 'user@example.com',
'website' => 'https://flatcoding.com',
'age' => '30',
'price' => '19.99'
];
// Define validation rules
$filters = [
'email' => FILTER_VALIDATE_EMAIL,
'website' => FILTER_VALIDATE_URL,
'age' => FILTER_VALIDATE_INT,
'price' => FILTER_VALIDATE_FLOAT
];
// Apply filters
$validatedData = filter_var_array($data, $filters);
// Check for validation errors
if (in_array(false, $validatedData, true)) {
echo "Invalid input detected.";
} else {
print_r($validatedData);
}Output:
Array
(
[email] => user@example.com
[website] => https://flatcoding.com
[age] => 30
[price] => 19.99
)
Here is how it works:
FILTER_VALIDATE_EMAILhelp you to make sure the email is valid.FILTER_VALIDATE_URLchecks if the URL format is correct.FILTER_VALIDATE_INTmakes sureageis a valid integer.FILTER_VALIDATE_FLOATcheckespriceis a valid decimal number.
This method validates multiple input types at once.
Example 3: Customize Filter with filter_var_array for Advanced Validation
You can customize filter_var_array() using advanced validation options like range limits, required formats, and flags.
// Sample input data (usually from $_POST or $_GET)
$data = [
'username' => 'JohnDoe123',
'email' => 'user@example.com',
'age' => '25',
'website' => 'https://example.com',
'ip' => '192.168.1.1'
];
// Define custom filters
$filters = [
'username' => [
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return preg_match('/^[a-zA-Z0-9_]{5,20}$/', $value) ? $value : false;
}
],
'email' => FILTER_VALIDATE_EMAIL,
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18, 'max_range' => 65]
],
'website' => [
'filter' => FILTER_VALIDATE_URL,
'flags' => FILTER_FLAG_PATH_REQUIRED
],
'ip' => FILTER_VALIDATE_IP
];
// Apply filters
$validatedData = filter_var_array($data, $filters);
// Check for validation errors
if (in_array(false, $validatedData, true)) {
echo "Invalid input detected.";
} else {
print_r($validatedData);
}
Output:
Invalid input detected.
Here is how it works:
- I used
FILTER_CALLBACKwith a regex pattern. Only allows letters, numbers, and underscores (5-20 characters). - In the age we make sure the age is between 18 and 65.
- It also requires a valid URL with a path (
FILTER_FLAG_PATH_REQUIRED). - We also check for a valid IP format.
This method provides stricter validation and more control over input processing.
Wrapping Up
You learned in this article how filter_var_array() to make input validation simple and sanitization in PHP. You also saw practical examples of validating form data and emails.
Also, you learned how to validate URLs and numbers with advanced filtering options.
Here is a quick recap:
filter_var_array()processes multiple inputs at once using different filters.- You can sanitize and validate form data to prevent invalid input.
- It supports email, URL, integer, and float validation.
- Advanced filtering allows custom validation with
FILTER_CALLBACK, range checks, and flags.
If you need more PHP tutorials, click here.
FAQ’s
What is filter_var_array() used for?
How is filter_var_array() different from filter_var()?
Can I use filter_var_array() to sanitize input?
What happens if a value fails validation?
Does filter_var_array() remove missing keys?
Similar Reads
PHP 5 added support for classes and interfaces. This made object-oriented code possible with one feature being polymorphism. That means…
PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…
You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…
let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…
In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…
PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…
At times, you may need to check if a row exists to avoid duplication when inserting or to prevent issues…
The filter_input_array() filters multiple inputs in PHP at once. It helps you to clean and validate data. Understand the filter_input_array…
Filtering data is a big part of getting the right information to show up. That is where the WHERE clause…
If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at…