Computers aren’t good at interpreting things unless we can give them rules on how to do so. Case in point is sorting with mixed data.

For example, which of these would you place first in a list?

NCC-1701
or
NCC-173

We see NCC- as the same in both, then we see 173 is less than 1701 so NCC-173 would go first. But a computer sorting would compare the characters one by one. NCC-17 are the same, then 0 and 3 are compared. NCC-1701 would go first using that method.

natsort() attempts to sort like a human might. As with the other sort functions, the original array is changed. This function keeps the associated keys in place.

$arr = array('bird_5.png',
             'bird_8.png',
             'bird_1.png',
             'bird_12.png');
 
sort($arr);
/*
array (
  0 => 'bird_1.png',
  1 => 'bird_12.png',
  2 => 'bird_5.png',
  3 => 'bird_8.png'
)
*/
 
natsort($arr);
/*
array (
  2 => 'bird_1.png',
  0 => 'bird_5.png',
  1 => 'bird_8.png',
  3 => 'bird_12.png'
)
*/

Be careful when attempting to sort zero padded numbers as strings. The results may be unexpected.

$arr = array('0007',
             '0004',
             '0010',
             '143',
             '6',
             '7',
             '8',
             '9',
             '10');
 
sort($arr);
/*
array (
  0 => '0004',
  1 => '6',
  2 => '7',
  3 => '0007',
  4 => '8',
  5 => '9',
  6 => '0010',
  7 => '10',
  8 => '143'
)
*/
 
natsort($arr);
/*
array (
  1 => '0004',
  0 => '0007',
  2 => '0010',
  4 => '6',
  5 => '7',
  6 => '8',
  7 => '9',
  8 => '10',
  3 => '143'
)
*/