filter_var() function in PHP

The filter_var() function is used to filter a variable with a specified filter. It provides a convenient way to validate and sanitize data in PHP applications.

Syntax

filter_var(variable, filter, options)

Parameters

  • variable − The value to filter

  • filter − The filter ID that specifies the filter to apply

  • options − Optional flags or options for the filter

Return Value

The filter_var() function returns the filtered data on success, or FALSE on failure.

Example 1: Email Validation

This example demonstrates validating an email address using FILTER_VALIDATE_EMAIL ?

<?php
    $myEmail = "examplee@demo.com";
    if (filter_var($myEmail, FILTER_VALIDATE_EMAIL)) {
        echo "$myEmail = valid email address";
    } else {
        echo "$myEmail = invalid email address";
    }
?>
examplee@demo.com = valid email address

Example 2: Integer Validation with Range

This example shows how to validate an integer within a specific range ?

<?php
    $int = 120;
    $min = 1;
    $max = 100;
    
    if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range" => $max)))) {
        echo "$int is valid";
    } else {
        echo "$int is not valid - must be between $min and $max";
    }
?>
120 is not valid - must be between 1 and 100

Example 3: Sanitizing a String

This example demonstrates removing unwanted characters from a string ?

<?php
    $string = "Hello @#$% World!";
    $sanitized = filter_var($string, FILTER_SANITIZE_STRING);
    echo "Original: $string<br>";
    echo "Sanitized: $sanitized";
?>
Original: Hello @#$% World!
Sanitized: Hello  World!

Conclusion

The filter_var() function is essential for validating and sanitizing user input in PHP. It supports various filters for emails, URLs, integers, and custom validation rules with options.

Updated on: 2026-03-15T07:32:53+05:30

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements