w3resource

PHP Exercises: Valid an email address


38. Email Validation

Write a PHP program to valid an email address.

Sample Solution:

PHP Code:

<?php
// Function to validate an email address
function valid_email($email)
{
    // Trim any leading or trailing whitespaces from the email
    $result = trim($email);

    // Check if the trimmed email is a valid email address
    if (filter_var($result, FILTER_VALIDATE_EMAIL)) 
    {
        // If valid, return "true"
        return "true";
    } 
    else 
    {
        // If not valid, echo "false"
        echo "false";
    }
}

// Test the function with valid and invalid email addresses
echo valid_email("[email protected]") . "\n";
echo valid_email("abc#example.com") . "\n";
?>

Explanation:

  • Define Function valid_email:
    • The function valid_email($email) checks if the provided email address is valid.
  • Trim Whitespace:
    • trim($email) removes any leading or trailing whitespace from the email input and assigns it to $result.
  • Validate Email Format:
    • filter_var($result, FILTER_VALIDATE_EMAIL) checks if $result is a valid email address format.
    • If valid, the function returns "true".
    • If invalid, it prints "false".
  • Test Cases:
    • The function is tested with "[email protected]" (valid) and "abc#example.com" (invalid). The results are printed.

Output:

true                                                        
false       

Flowchart:

Flowchart: Valid an email address

For more Practice: Solve these Related Problems:

  • Write a PHP script to validate email addresses using custom regular expressions with support for new TLDs.
  • Write a PHP script to process a list of email addresses, segregating valid and invalid emails.
  • Write a PHP script to validate an email address and confirm that its domain has a valid MX record.
  • Write a PHP script to trim, sanitize, and validate an email address using filter_var and additional custom checks.


Go to:


PREV : Sum of Primes Below 100.
NEXT : Get File Size.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.