The natsort Function

The natsort function sorts an array as a human would. This function preserves the associations between keys and values. This algorithm is called natural ordering.

The function modifies the array itself.

Syntax

phpnatsort(array &$array, int $flags = SORT_REGULAR): bool

Example

Let's sort an array using the regular sort function:

php<?php
  $arr = [
    'img12.png',
    'img10.png',
    'img2.png',
    'img1.png',
  ];
  
  sort($arr);
  var_dump($arr);
?>

Code execution result:

php[
  'img1.png',
  'img10.png',
  'img12.png',
  'img2.png',
]

Example

Now let's perform natural sorting using the natsort function:

php<?php
  $arr = [
    'img12.png',
    'img10.png',
    'img2.png',
    'img1.png'
  ];
  
  natsort($arr);
  var_dump($arr);
?>

Code execution result:

php[
  'img1.png',
  'img2.png',
  'img10.png',
  'img12.png',
]

See Also

  • the sort function,
    which sorts by element values in ascending order
  • the rsort function,
    which sorts by element values in descending order
  • the ksort function,
    which sorts by keys in ascending order
  • the krsort function,
    which sorts by keys in descending order
  • the asort function,
    which sorts by element values in ascending order while preserving keys
  • the arsort function,
    which sorts by element values in descending order while preserving keys
  • the natcasesort function,
    which sorts naturally in a case-insensitive manner
  • the usort function,
    which sorts using a callback function
  • the uksort function,
    which sorts by keys using a callback function
  • the uasort function,
    which sorts using a callback function while preserving keys
  • the array_multisort function,
    which sorts multiple arrays