natsort

Sort an array using a "natural order" algorithm

Syntax

natsort ( array &$array ) : bool

Parameters

array

The input array.

Return

Returns TRUE on success or FALSE on failure.

Examples

1

<?

$array = array("d" => "Lemon", "a" => "orange", "B" => "Banana", "C" => "apple");

natsort($array);

foreach ($array as $key => $value) {
    echo "$key => $value\n";
}

?>
B => Banana
d => Lemon
C => apple
a => orange

2

<?

$array1 = $array2 = array("img12.svg", "img10.svg", "img2.svg", "img1.svg", "IMG4.svg", "IMG3.svg");

asort($array1);
echo "asort:\n";
print_r($array1);

natsort($array2);
echo "natsort:\n";
print_r($array2);

?>
asort:
Array
(
    [5] => IMG3.svg
    [4] => IMG4.svg
    [3] => img1.svg
    [1] => img10.svg
    [0] => img12.svg
    [2] => img2.svg
)
natsort:
Array
(
    [5] => IMG3.svg
    [4] => IMG4.svg
    [3] => img1.svg
    [2] => img2.svg
    [1] => img10.svg
    [0] => img12.svg
)

3

<?

$array1 = $array2 = array('-5', '3', '-2', '0', '-1000', '9');

asort($array1);
echo "asort:\n";
print_r($array1);


natsort($array2);
echo "natsort:\n";
print_r($array2);

?>
asort:
Array
(
    [4] => -1000
    [0] => -5
    [2] => -2
    [3] => 0
    [1] => 3
    [5] => 9
)
natsort:
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [1] => 3
    [5] => 9
)

PHP

Home Menu