views:

23

answers:

2

I have a list of domain names, for example:

domain1.com
domain2.com
domainxxx2.com
dom.com

from that list I want to get:

length 7 [2]
length 10 [1]
length 3 [1]

I know how to split the tld and count each domain length, but dont know how to group and count those with the same length.

I would like to do it on PHP.

A: 

Quick and dirty and untested:

$lengths = [];
for ($i = 1; $i <= 255; $i++) {
    foreach ($domains as $domain) {
        if (strlen($domain) === $i) {
            $lengths[$i][] = $domain;
        }
    }
}
stevelove
Use Pickle's answer instead. It's much faster.
stevelove
Haven't used your code but it helped me to put this together: **[foreach($domains as $domain){ $tmp = explode(".", $domain); $length = strlen(trim($tmp[0])); $count[$length] = $count[$length]+1;}print_r($count);]**
gtilx
+1  A: 

Quicker & cleaner but still untested

$sorted = array();
foreach($domains as $domain)
{
    $sorted[strlen($domain)][] = $domain;
}
Pickle
Yes, definitely quicker than mine in terms of execution speed. :) When I described mine as "quick" I was referring to the amount of time I put into thinking of a solution.
stevelove
Ya, that was clear. Not sure why I prefaced my code like I did.
Pickle