PHP filters extend beyond single scalar values. You can filter entire arrays using filter_var_array(), apply custom callback functions with FILTER_CALLBACK, and supply advanced behavior flags.
flowchart TD
A["Input Dataset / Array"] --> B{"Choose Advanced Filter Method"}
B -- Bulk Array Filtering --> C["filter_var_array($data, $schema)"]
B -- Custom Function Logic --> D["filter_var($input, FILTER_CALLBACK, ['options' => $func])"]
B -- Filter Flags --> E["filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)"]
<?php
declare(strict_types=1);
// 1. Bulk Input Schema Validation using filter_var_array()
$inputData = [
'username' => ' maksudur ',
'age' => '28',
'email' => '[email protected]',
'website' => 'https://kodersolution.com'
];
$validationSchema = [
'username' => [
'filter' => FILTER_CALLBACK,
'options' => fn(string $val): string => strtoupper(trim($val))
],
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18, 'max_range' => 100]
],
'email' => FILTER_VALIDATE_EMAIL,
'website' => FILTER_VALIDATE_URL,
];
$validatedData = filter_var_array($inputData, $validationSchema);
// 2. Rejecting Private IP Addresses with Flags
$publicIP = "8.8.8.8";
$privateIP = "192.168.1.1";
$isPublic = filter_var($privateIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
echo "Processed Data Array:
";
print_r($validatedData);
echo "Is '192.168.1.1' Public IP?: " . ($isPublic !== false ? "Yes" : "No (Private IP Rejected)") . "
";
filter_var_array() to sanitize and validate complex form payloads in a single line.FILTER_CALLBACK for Custom Sanitizers: Clean complex string formatting while retaining standard filter syntax.FILTER_FLAG_NO_PRIV_RANGE for Public IP Checks: Essential when validating server webhooks or external API client IP addresses.Write a filter_var() call using FILTER_CALLBACK that converts a string to lowercase and trims whitespace!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.