Sorting ip address in an application

I've built an application where IP address can't be sorted out. I am using object oriented PHP. All the ip address value has been saved as varchar and when I sort that out, it looks like this:

192.168.111.1>192.168.111.100>192.168.111.101>....>192.168.111.2>192.168.111.200>...>192.168.111.3>192.168.111.300>.......

but the sorting should be like this:

192.168.111.1>192.168.111.2>192.168.111.3>....>192.168.111.99>192.168.111.100>.....192.168.111.300

I don't know how do I sort it out, could anybody help me out? Thanks in Advance.

Upvotes: 1

Views: 2143

Answers (2)

briskola
briskola

Reputation: 66

Waaay late to the party, but recently I needed something similar with a twist (my IP addresses were as the array's index, ksort() would not collaborate beyond the 2st octet)... and the solution might come in handy to someone else. I leveraged the ip2long() and long2ip() functions, like:

$array = [ '192.168.200.200', '192.168.10.10', '172.16.5.5', '172.16.20.20' ];
foreach ($array as $key => $value) $array[$key] = ip2long($value);
sort($array);
foreach ($array as $key => $value) $array[$key] = long2ip($value);
print_r($array);

Array
(
    [0] => 172.16.5.5
    [1] => 172.16.20.20
    [2] => 192.168.10.10
    [3] => 192.168.200.200
)

Upvotes: 0

Daan
Daan

Reputation: 12246

Try natural ordering: natsort

$array = ['192.168.1.1', '192.168.1.101', '192.168.1.2', '192.168.1.102', '192.168.1.3'];
natsort($array);
echo "\nNatural order sorting\n";
print_r($array);

Upvotes: 6

Related Questions