PHP - Array Array Sorting

Introduction

An array can be sorted in different ways.

By default, the array is sorted by the order in which the elements were added to it.

You can sort an array by its key or by its value, both ascending and descending.

When sorting an array by its values, you can choose to preserve their keys or to generate new ones as a list.

Here are some array sorting function:

Name

Sorts by

Maintains key
association
Order of sort

sort
Value
No
Low to high
rsort
Value
No
High to low
asort
Value
Yes
Low to high
arsort
Value
Yes
High to low
ksort
Key
Yes
Low to high
krsort
Key
Yes
High to low

These functions always take one argument, the array, and they do not return anything.

Instead, they directly sort the array we pass to them.

Demo

<?php
     $properties = [ //  www  . j a va2  s  . c  o m
        'firstname' => 'T', 
        'surname' => 'R', 
        'house' => 'S' 
     ]; 
     $properties1 = $properties2 = $properties3 = $properties; 
     sort($properties1); 
     var_dump($properties1); 
     asort($properties3); 
     var_dump($properties3); 
     ksort($properties2); 
     var_dump($properties2); 
?>

Result

Here, we initialize an array with some key values and assign it to $properties.

Then we create three variables that are copies of the original array-the syntax should be intuitive.

The first function, sort, orders the values alphabetically.

asort orders the values in the same way, but keeps the association of key-values.

Finally, ksort orders the elements by their keys, alphabetically.

Function names

So, here are some tips to remember what each sorting function does:

An a in the name means associative, and thus, will preserve the key-value association.

An r in the name means reverse, so the order will be from high to low.

A k means key, so the sorting will be based on the keys instead of the values.

Related Topics