Advanced PHP Filters

PHP provides advanced filtering functions that allow you to create custom filter rules and filter data based on specific criteria. These functions include filter_list(), filter_id(), and filter_var_array().

Available Filters

<?php
$filters = filter_list();
foreach ($filters as $filter) {
    echo $filter . "\n";
}
?>

Explanation: This example uses filter_list() to list all available filters.

Filter ID

<?php
$filterId = filter_id("FILTER_VALIDATE_EMAIL");
echo $filterId; // Outputs: 2047
?>

Explanation: This example uses filter_id() to get the ID of the FILTER_VALIDATE_EMAIL filter.

Filtering an Array

<?php
$data = array(
    "name" => "John Doe",
    "email" => "user@example.com",
    "url" => "https://www.example.com",
    "age" => 30,
    "phone" => "123-456-7890",
);
$rules = array(
    "name" => FILTER_SANITIZE_STRING,
    "email" => FILTER_VALIDATE_EMAIL,
    "url" => FILTER_VALIDATE_URL,
    "age" => FILTER_VALIDATE_INT,
    "phone" => FILTER_SANITIZE_NUMBER_INT,
);
$filteredData = filter_var_array($data, $rules);
print_r($filteredData);
?>

Explanation: This example demonstrates how to filter an array of data using filter_var_array(). Each field is filtered according to the specified rules, ensuring that the data is sanitized and validated before use.

Custom Filters

<?php
function custom_filter($value) {
    return ($value > 0) ? $value : 0; // Ensure the value is non-negative
}
$input = -5;
$filteredValue = custom_filter($input);
echo $filteredValue; // Outputs: 0
?>

Explanation: This example shows how to create a custom filter function that ensures a value is non-negative. You can use this approach to implement more complex filtering logic as needed.