- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
Sorting Arrays
PHP offers all kinds of ways to sort the data in arrays, starting with the simple sort function, which you use on arrays with numeric indexes. In the following example, we create an array, display it, sort it, and then display it again:
<?php $fruits[0] = "tangerine"; $fruits[1] = "pineapple"; $fruits[2] = "pomegranate"; print_r($fruits); sort($fruits); print_r($fruits); ?>
Here are the results—as you can see, the new array is in sorted order; note also that the elements have been given new numeric indexes:
Array ( [0] => tangerine [1] => pineapple [2] => pomegranate ) Array ( [0] => pineapple [1] => pomegranate [2] => tangerine )
You can sort an array in reverse order if you use rsort instead:
<?php $fruits[0] = "tangerine"; $fruits[1] = "pineapple"; $fruits[2] = "pomegranate"; print_r($fruits); rsort($fruits); print_r($fruits); ?>
Here's what you get:
Array ( [0] => tangerine [1] => pineapple [2] => pomegranate ) Array ( [0] => tangerine [1] => pomegranate [2] => pineapple )
What if you have an array that uses text keys? Unfortunately, if you use sort or rsort, the keys are replaced by numbers. If you want to retain the keys, use asort instead, as in this example:
<?php $fruits["good"] = "tangerine"; $fruits["better"] = "pineapple"; $fruits["best"] = "pomegranate"; print_r($fruits); asort($fruits); print_r($fruits); ?>
Here are the results:
Array ( [good] => tangerine [better] => pineapple [best] => pomegranate ) Array ( [better] => pineapple [best] => pomegranate [good] => tangerine )
You can use arsort to sort arrays such as this in reverse order. What if you wanted to sort an array such as this one based on keys, not values? Just use ksort instead. To sort by reverse by keys, use krsort. You can even define your own sorting operations with a custom sorting function you use with PHP's usort.