Search code examples
phparraysemailemail-validationdomain-name

How to check email id's with specific domain from the array of email id's in PHP?


I've an array of email ids. I want to check each and every email id for it's domain. Actually, I've to parse over this array whenever there is email id found with no '.edu' domain, error message should be thrown as 'Please enter valid .edu id' and further emails from the array should not be checked.

How should I achieve this in efficient and reliable way?

Following is my code of array which contains the email ids. The array could be empty, contain single element or multiple element. It should work for all of these scenarios with proper validation and error messages.

$aVals = $request_data;
$aVals['invite_emails'] = implode(', ', $aVals['invite_emails']);

$aVals['invite_emails'] contains the list of email ids received in request.

Please let me know if you need any further information regarding my requirement if it's not clear to you.

Thanks in advance.


Solution

  • You can do something like this,

    Updated:

    // consider $aVals['invite_emails'] being your array of email ids
    // $aVals['invite_emails'] = array("[email protected]", "[email protected]");
    
    if(!empty($aVals['invite_emails'])){  //checks if the array is empty
        foreach($aVals['invite_emails'] as $email){  // loop through each email
            $domains = explode(".",explode("@",$email)[1]); // extract the top level domains from the email address
            if(!in_array("edu", $domains)){  // check if edu domain exists or not
                echo "Please enter valid .edu id";
                break;  // further emails from the array will not be checked
            }
        }
    }