Sorting Arrays

Sorting is perhaps the greatest magic you can perform on an array. Thanks to the functions PHP offers to achieve just this, you can truly bring order from chaos. This section introduces some functions that allow you to sort both numerically indexed and associative arrays.

Sorting Numerically Indexed Arrays with sort()

sort() accepts an array as its argument and sorts it either alphabetically if any strings are present or numerically if all elements are numbers. The function doesn’t return any data, transforming the array you pass it. Note that it differs from Perl’s sort() function in this respect. The following fragment of code initializes an array of single character strings, sorts it, and outputs the transformed array:

 $an_array ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.