Home Menu

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.png", "img10.png", "img2.png", "img1.png", "IMG4.png", "IMG3.png");

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

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

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

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

JesusBible
HTMLCSSJSPHPSVGMore
AboutTerms