Sort an array dataset in PHP

Posted on November 9, 2008

It may be necessary to sort a dataset after a SQL request. And in a general case, I prefer using this function instead of dealing with the ORDER BY and LIMIT clauses.

So I wrote this method (which is part of my Utils class, in my own framework):

* Sort a dataset
* @param array $dataset
* @param string $sortby
* @param string $order (can be either 'ASC' or 'DESC')
public static function sortDataset($dataset,$sortby,$order = 'ASC') {
$columns = array();
foreach ($dataset as $key => $row) {
foreach($row as $k => $v) {
$columns[$k][$key] = $v;
if (array_key_exists($sortby,$columns)) {
$params = array();
$params[] = &$columns[$sortby];
$params[] = constant('SORT_'.$order);
foreach($columns as $key => $column) {
if ($key != $sortby) {
$params[] = &$column;
$params[] = SORT_ASC;
$params[] = &$dataset;
return $dataset;

Usage example

$array = array();
$array[] = array('id' => 1, 'name' => 'Foo');
$array[] = array('id' => 3, 'name' => 'Bar');
$array[] = array('id' => 8, 'name' => 'Anon');
$array[] = array('id' => 2, 'name' => '4chan');
$arraySortedByName = sortDataset($array,'name');
$arraySortedByID = sortDataset($array,'id','DESC');

$arraySortedByName is the same array with lines sorted by the name key.

$arraySortedByID is the same array with lines sorted by the ID key in descendant order.

It’s quite usefull, I don’t understand why there is no such a native function in PHP…

In the example, I define the array manualy but you can imagine it represent the result lines of an SQL query. I hope it’ ll help someone!

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.