Hi,
I wrote a little piece of code which I think is not a very good one. Please have a look:

$emaillist = array('johann@keppler.com','bill@gates.com','marco@polo.com');
$blacklisteddomains = ('keppler.com','gates.com');
$blacklistedemails =  filter_blacklisted($emaillist, $blacklisteddomains);

/** creates a list of blacklisted emails using a blacklisted domains list */
function filter_blacklisted($emaillist, $blacklisteddomains){
	$blacklistedemails = array();

foreach($emaillist as $email){
	foreach($blacklisteddomains as $domain){
		if(stripos($email,$domain)){
			array_push($blacklistedemails,$email);
		}
	}
}
return $blacklistedemails;
}

I don't think nesting foreach is necessary. Is there a faster or better way to do so?

Thanks for everyone who is helping me to think in the right direction!

Cheers,
Sto

    To see if the domains are in the array you can use the in_array() function. If it is... then you find the key of the blacklisted e-mail but using array_key() and then unset() the array key to remove it from the list.

      To see if the domains are in the array you can use the in_array() function.

      One would have to extract the domain portion of the email address first.

      I think that in terms of efficiency the implementation is fine. However, there is an oversight: suppose someone has the email address keppler.com@example.com. Your code would blacklist that email address even though example.com is not a blacklisted domain name, simply because keppler.com is blacklisted.

        I think the way I would do this would be something like this:

        <?PHP
        $blacklisted = array('@microsoft.com', '@ibm.com');
        $emails = array('bill@microsoft.com', 'blue@ibm.com', 'test@notblacklisted.com');
        foreach ($emails as $email) {
            if (in_array(strstr($email, '@'), $blacklisted)) {
                // blacklisted domain
                echo 'blacklist'."\n";
            }
            else {
                // okay to go
                echo 'okay'."\n";
            }
        }
        ?>
        

        Edit: my bad, this'll just tell you what's blacklisted and what's not. You'd just array_push onto another array of blacklisted emails instead of echo 'blacklist', if that's what you wanted. I was just showing a way to do it without nesting the foreaches, and it shouldn't match something like keppler.com@example.com

          Write a Reply...