Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

filter_var()

Example

Verify if $email is a valid email address.

<?php
$email = [email protected];

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo(“$email is a valid email address”);
else {
  echo(“$email is not a valid email address”);
}
?>

Definition and Usage

The filter_var() function applies a specified filter to a variable.

Syntax

filter_var(var, filtername, options)

Parameter Values

 

Parameter

Description

var

Mandatory. The variable to be filtered.

filtername

Optional. Specifies the filter ID or name to use. The default is FILTER_DEFAULT, which applies no filtering.

options

Optional. Specifies one or more flags or options to use. Refer to each filter’s documentation for available options and flags.

Technical Details

Return Value:

Returns the filtered data if successful, or FALSE if it fails.

PHP Version:

5.2+

More Examples

The following example both sanitizes and validates an email address:

Example

First, remove any illegal characters from $email, and then verify if it is a valid email address.

<?php
$email = [email protected];

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo(“$email is a valid email address”);
else {
    echo(“$email is not a valid email address”);
}
?>