Jump to: navigation, search

Php natsort

From w3cyberlearnings

Contents

PHP function natsort

This function sorts array by using the natural order algorithm. Natural order algorithm works this way: 1 is before 2, 500 is before 501.

Syntax natsort

  • array: array input
natsort(array);

For case insensitive natural order sorting uses natcasesort() function.

Example 1

<?php

$tfile = array(
	 'file01',
	 'file02',
	 'file30',
	 'file1',
	 'file5',
	 'File51',
	 'File30',
	 'file06'
);

natsort($tfile);
print_r($tfile);
?>

Output

Array
(
    [6] => File30
    [5] => File51
    [0] => file01
    [1] => file02
    [7] => file06
    [3] => file1
    [4] => file5
    [2] => file30
)

Example 2

<?php

$name_s = array(
	 'file1' => 3,
	 'file3' => 1,
	 'file100' => 100,
	 'file10' => 100,
	 'file11' => 300,
	 'file9' => 301
);

natsort($name_s);
print_r($name_s);
?>

Output

  • The array's values arrange in order.
Array
(
    [file3] => 1
    [file1] => 3
    [file10] => 100
    [file100] => 100
    [file11] => 300
    [file9] => 301
)

Related Links


Navigation
Web
SQL
MISC
References