PHP sort array - Sort array by key


Home - Tutorials - Basics

In this tutorial I will show you how to sort a PHP array easy and fast. You will learn the most important PHP built in array sorting functions.

Tutorial info:


Name:PHP sort array
Total steps:4
Category:Basics
Level:Beginner

Bookmark PHP sort array



Bookmark and Share

Step 4 - Sort array by key


PHP sort array



As you may suppose PHP has some function to sort an associative array by keys. And you are right. These functions are the ksort and krsort. As before the krsort sorts the array in a reverse order. The usage is the same as before so your code will be:

Code:
  1. ksort($colorList);
  2. foreach ($colorList as $key => $value) {
  3. echo $key.' - '.$value.'<br/>';
  4. }
which results the following output:
Output:
  1. apple - red
  2. grass - green
  3. night - black
  4. sky - blue
  5. wall - white
The usage of krsort is straightforward.

Beside this PHP has some more advanced sorting functions:
array_multisort — Sort multiple or multi-dimensional arrays
natcasesort — Sort an array using a case insensitive "natural order" algorithm
natsort — Sort an array using a "natural order" algorithm
uasort — Sort an array with a user-defined comparison function and maintain index association
uksort — Sort an array by keys using a user-defined comparison function
usort — Sort an array by values using a user-defined comparison function





Previous Step of PHP sort array


Tags: php sort array, sort array, php, array, sort



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0556