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
The PHP object is an instance from the PHP class or the main data structure that is already been created…
The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…
Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…
When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…
actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to…
There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…
Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…
The array_key_last gives you the last key in an array and works with numeric and associative arrays in PHP. It…
In some cases, you need to handle a lot of data or simply try to open a file, or read…
A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming…