What potential pitfalls should be considered when separating email addresses by domain in PHP?

When separating email addresses by domain in PHP, a potential pitfall to consider is the presence of invalid or malformed email addresses. To handle this, you can use PHP's built-in filter_var function with the FILTER_VALIDATE_EMAIL filter to validate each email address before extracting the domain.

$emailAddresses = ['john@example.com', 'invalid_email', 'jane@example.com'];

$domains = [];
foreach ($emailAddresses as $email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $domain = explode('@', $email)[1];
        $domains[] = $domain;
    }
}

print_r($domains);