skos
skos

Reputation: 4212

Filtering Emails By Domain Names

Lets say I have two arrays -

$EmailList1 = array("[email protected]", "[email protected]", "[email protected]");
$EmailList2 = array("[email protected]", "[email protected]", "[email protected]");

Now I'd like my new array to be [[email protected], [email protected]]

The reason [email protected] was omitted because it has domain (domain1.com) which already is present in $EmailList1

My approach would be to first get all the domains of $EmailList1, storing it into an array, looping through each item of $EmailList2 and then getting the result.

Is this the right way or there could be a better way ?

Upvotes: 0

Views: 65

Answers (3)

Baba
Baba

Reputation: 95121

All you need is

$EmailList1 = array("[email protected]","[email protected]","[email protected]");
$EmailList2 = array("[email protected]","[email protected]","[email protected]");

$diff = array_udiff($EmailList2, $EmailList1, function ($a, $b) {
    return strstr($a, '@') === strstr($b, '@') ? 0 : 1;
});

echo "<pre>";
var_dump($diff);

Output

array (size=2)
  1 => string '[email protected]' (length=15)
  2 => string '[email protected]' (length=15)

Upvotes: 1

Hadi
Hadi

Reputation: 2905

try this -

<?php
$EmailList1 = array("[email protected]", "[email protected]", "[email protected]");
$EmailList2 = array("[email protected]", "[email protected]", "[email protected]");

foreach($EmailList1 as $email){
  $emailArray = explode('@',$email);
  $domainArray[] = $emailArray[1];
}

$domains = array_unique($domainArray);

foreach($EmailList2 as $email){
  $emailArray = explode('@',$email);
  if(!in_array($emailArray[1], $domains) && !array_search($emailArray[1], $domains)){
    $sorted_emails[] = $email;
  }
}

print_r($sorted_emails);
?>

Upvotes: 0

mallix
mallix

Reputation: 1429

Try:

$uniqueEmailsArray = array_unique(array_merge($EmailList1 , $EmailList2));

Upvotes: 0

Related Questions