Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alphabetically sort a php array after a certain character in a string

I have two php arrays. And have a different sorting question for each of these arrays:

1) First contains list of domains:

values[0] = "absd.com";
values[1] = "bfhgj.org";
values[2] = "sdfgh.net";
values[3] = "sdff.com";
values[4] = "jkuyh.ca";

I need to sort this array alphabetically by DOMAIN value, in other words by the value after the '.', so the sorted domain will be as follows:

values[0] = "jkuyh.ca";
values[1] = "absd.com";
values[2] = "sdff.com";
values[3] = "sdfgh.net";
values[4] = "bfhgj.org";

2) I also have second array that contains "double" domain values:

values[0] = "lkjhg.org.au";
values[1] = "bfhgj.co.uk";
values[2] = "sdfgh.org.uk";

I need to sort this array alphabetically by DOUBLE DOMAIN value, in other words by the value after the first instance of '.' in domain, so the sorted domain will be as follows:

values[1] = "bfhgj.co.uk";
values[0] = "lkjhg.org.au";
values[2] = "sdfgh.org.uk";

How do I tackle this issue? sort() approach sorts only based on first letter...

like image 630
Acidon Avatar asked Jan 17 '26 18:01

Acidon


1 Answers

usort is the answer.

Try this:

usort($values,function($a,$b) {
    return strcasecmp(
        explode(".",$a,2)[1],
        explode(".",$b,2)[1]
    );
});

(Note that you will need to store the result of explode in a temporary variable and access that separately, if you're still using PHP 5.3 or older)

like image 83
Niet the Dark Absol Avatar answered Jan 19 '26 09:01

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!