Array Functions
Advertisements

PHP natsort() Function

Topic: PHP Array ReferencePrev|Next

Description

The natsort() function sorts an array using a "natural order" algorithm.

The keys are preserved, i.e. the key-to-value mapping will remain unchanged by the sort operation.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Changelog: Since PHP 5.2.10+, zero padded numeric strings (e.g., '00004') now ignore the 0 padding.
Version: PHP 4+

Syntax

The basic syntax of the natsort() function is given with:

natsort(array);

The following example shows the natsort() function in action.

<?php
// Sample array
$images = array("img5.png", "img10.png", "img2.png", "img1.png");

// Standard sorting
sort($images);
print_r($images);

// Natural order sorting
natsort($images);
print_r($images);
?>

Tip: The natsort() function implements a sort algorithm that orders the alphanumeric strings in the way a human being would. This is described as a "natural ordering".


Parameters

The natsort() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to be sorted.

More Examples

Here're some more examples showing how natsort() function actually works:

The following example shows how negative numeric strings will be sorted in natural ordering.

<?php
// Sample array
$array = array("-5", "10", "-2", "0", "-10", "8", "1");

// Standard sorting
sort($array);
print_r($array);

// Natural order sorting
natsort($array);
print_r($array);
?>

The following example shows how zero padded numeric strings will be sorted in natural ordering.

<?php
// Sample array
$array = array("07", "8", "10", "007", "09", "011", "0");

// Standard sorting
sort($array);
print_r($array);

// Natural order sorting
natsort($array);
print_r($array);
?>
Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.