Jump to content

[SOLVED] Sorting an array of emails by domain


mikeg542

Recommended Posts

Say I have a list of emails like so:

$emails = array('[email protected]','[email protected]','[email protected]','[email protected]');

 

And want it sorted to be in the order: [email protected], [email protected], [email protected], [email protected].

 

 

My idea was to assign an unchangable value to the two parts of each (as in , explode them based on @, assign a value to each pair, sort by the second part then attach the first part back on based on the matching values)

 

firstly, is this possible? and second, is it efficient for what I'm aiming for?

$emails = array('[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]');

echo 'Unsorted<br />';
print_r($emails);
echo '<br />';

function domainSort($a, $b) {
list($aMailbox,$aDomain) = explode('@',$a);
list($bMailbox,$bDomain) = explode('@',$b);

    if ($aDomain == $bDomain) {
    return ($aMailbox < $bMailbox) ? -1 : 1;
    }
    return ($aDomain < $bDomain) ? -1 : 1;
}

usort($emails,'domainSort');

echo 'Sorted<br />';
print_r($emails);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.