PhpDig.net

What is PhpDig?
PhpDig is a PHP MySQL based
Web Spider & Search Engine.




natsort

Name

natsort — Sorts an array in ascending order by value, using a natural sorting algorithm.

Synopsis

void natsort(array);
array array: Array to sort

Returns

Nothing.

Description

This function simply sorts an array in ascending order by element value, keeping key/value relationships intact. However, the algorithm sorts the values as strings according to the rules typically used by humans to order alphanumeric strings. This gives a very natural result.

The basic idea is that any strings of digits embedded within the strings being sorted are compared according to their actual numeric values, and not according to the character codes of the individual digits. For instance, while in a normal computer sort the value b2 would be considered to be greater than b10 (since 1 comes before 2), a natural sorting algorithm looks at the values of the embedded numbers - in this case, 2 and 10 - and places b2 first.

This function also handles multiple numeric sequences within the same string and separated by non-digit characters.

Version

PHP 4 since 4.0RC2

Example

Example 52. Sort in natural order

$normal = $natural = array('b2', 'b10', 'a12', 'a7');
sort($normal);
echo "Normal sort using sort():\n";
print_r($normal);

$array = array('b2', 'b10', 'a12', 'a7');
natsort($natural);
echo "Natural sort using natsort():\n";
print_r($natural);

Output:
Normal sort using sort():
Array
(
    [0] => a12
    [1] => a7
    [2] => b10
    [3] => b2
)
Natural sort using natsort():
Array
(
    [3] => a7
    [2] => a12
    [0] => b2
    [1] => b10
)



PHP Functions Essential Reference. Copyright © 2002 by New Riders Publishing (Authors: Zak Greant, Graeme Merrall, Torben Wilson, Brett Michlitsch). This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). The authors of this book have elected not to choose any options under the OPL. This online book was obtained from http://www.fooassociates.com/phpfer/ and is designed to provide information about the PHP programming language, focusing on PHP version 4.0.4 for the most part. The information is provided on an as-is basis, and no warranty or fitness is implied. All persons and entities shall have neither liability nor responsibility to any person or entity with respect to any loss or damage arising from the information contained in this book.

Powered by: vBulletin Version 3.0.7
Copyright ©2000 - 2005, Jelsoft Enterprises Ltd.
Copyright © 2001 - 2005, ThinkDing LLC. All Rights Reserved.