PHP sort array


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 1 - Introduction


PHP sort array


From time to time you want to sort arrays. You maybe want to do it alphabetically or numerically, ascending or descending order. To do this PHP provide some usefull functions. In the next section I will show you how to use them. First of all we need a small example array to work with:

Code:
  1. $colorList = array("apple"=>"red",
  2. "grass"=>"green",
  3. "sky"=>"blue",
  4. "night"=>"black",
  5. "wall"=>"white");
Now if you display the array you will see the elements in the same order as they were defined. (If you don't know how to print an array then you can visit our PHP print array tutorial.) So if you use the following code to display the unsorted array elements:
Code:
  1. foreach ($colorList as $key => $value) {
  2. echo $key.' - '.$value.'<br/>';
  3. }

then your output will look like this:
Output:
  1. apple - red
  2. grass - green
  3. sky - blue
  4. night - black
  5. wall - white
So the next step is to sort this array.





Next 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
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0231