PHP to check if an email address is in a specific domain


Code Solution:

<?php
// Function to check if an email address is in a specific domain
function is_email_in_domain($email, $domain) {
  // Get the domain part of the email address
  $email_domain = explode('@', $email)[1];

  // Check if the email domain matches the specified domain
  return $email_domain === $domain;
}

// Test the function
$email = 'example@gmail.com';
$domain = 'gmail.com';

if (is_email_in_domain($email, $domain)) {
  echo 'The email address is in the specified domain.';
} else {
  echo 'The email address is not in the specified domain.';
}
?>

Explanation:

The is_email_in_domain() function takes two parameters: an email address and a domain name. It checks if the email address is in the specified domain by comparing the domain part of the email address with the specified domain.

Here’s how the function works:

  1. It uses the explode() function to split the email address into two parts: the username and the domain. The @ symbol is used as the delimiter.
  2. It assigns the domain part of the email address to the $email_domain variable.
  3. It compares the $email_domain variable with the specified domain using the === operator. The === operator checks for both value and type equality.
  4. The function returns true if the email domain matches the specified domain, and false otherwise.

How to Implement:

To use the is_email_in_domain() function, you can simply call it with the email address and the domain name as arguments. For example:

if (is_email_in_domain($email, $domain)) {
  // Do something if the email address is in the specified domain
} else {
  // Do something if the email address is not in the specified domain
}

You can use the is_email_in_domain() function to validate email addresses and to filter out email addresses that are not from a specific domain.