Home > database >  Sorting an array of addresses based on street number using PHP
Sorting an array of addresses based on street number using PHP

Time:04-27

I'm pulling in a list of street addresses from the MLS into my application, and am trying to figure out a way to sort that list numerically using PHP .. based on the street number.

For example ... if I have the following street addresses in my array ...

117 Thatch Palm Cove
1371 Royal Palm Way
174 W Coconut Palm Road
2323 Areca Palm Road
234 W Alexander Palm Road
303 E Alexander Palm Road
1739 Royal Palm Way

How would I sort this array in numerically ascending order (based on the street number) as follows?

117 Thatch Palm Cove
174 W Coconut Palm Road
234 W Alexander Palm Road
303 E Alexander Palm Road
1371 Royal Palm Way
1739 Royal Palm Way
2323 Areca Palm Road

I've already tried several of PHP's built in sort methods, but am apparently running into issues due to the alphanumeric - rather than purely numerical -- array items. Please advise.

Thanks, -- Yvan

CodePudding user response:

Something as simple as this should work:

$names_to_sort = array(
    "117 Thatch Palm Cove",
    "1371 Royal Palm Way",
    "174 W Coconut Palm Road",
    "2323 Areca Palm Road",
    "234 W Alexander Palm Road",
    "303 E Alexander Palm Road",
    "1739 Royal Palm Way"
);

natsort($names_to_sort);

CodePudding user response:

Got it!!!

function cmp($a, $b) {
    return strnatcmp($a["name"], $b["name"]);
}
                        
usort($addressesarray, 'cmp');
  • Related