Categories
PHP

Natural Order Sorting

Natural ordering is an alphanumeric sort order, it treated multiple digits as a single character. The natsort() and natcasesort functions do not take flags and are the same as called sort() (or sort(), rsort() etc.) with the SORT_NATURAL flag.

The natsort and natcasesort functions sort arrays using a Natural Order Sorting algorithm. Both functions are identical except the natcasesort function ignores the case. These functions implement a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. Both functions accept only one parameter, the input array.

<?php
 $a = ['A1','A3','B1','A22','B3','B22'];
 natsort ($a);
 print_r ($a);

/*Prints:
Array
(
    [0] => A1
    [3] => A3
    [1] => A22
    [2] => B1
    [5] => B3
    [4] => B22
)*/

The above code maintained the key/value association, replace natsort($a) line with sort($a, SORT_NATURAL) code if you want to reset/rearrange the array index:

 <?php
  //natsort ($a);
  sort ($a, SORT_NATURAL);
  print_r($a);

 /*Prints:
Array
(
    [0] => A1
    [1] => A3
    [2] => A22
    [3] => B1
    [4] => B3
    [5] => B22
) */

Follow this link to read about the array sorting flags.

Sorting IP Addresses

<?php
 $a = ['192.168.0.1',
       '192.168.0.254',
       '192.168.1.2',
       '192.168.0.233',
       '192.167.5.3'
];
 natsort ($a);
 print_r ($a);

/*Prints:
Array
(
    [4] => 192.167.5.3
    [0] => 192.168.0.1
    [3] => 192.168.0.233
    [1] => 192.168.0.254
    [2] => 192.168.1.2
)*/

More Posts on PHP Sorting Arrays: