← Back to Chapters

PHP Array Sorting Functions

? PHP Array Sorting Functions

ℹ️ Quick Overview

PHP provides multiple built-in array sorting functions that help arrange array elements in ascending or descending order. These functions can sort indexed arrays, associative arrays, or arrays based on keys or values.

? Key Concepts

  • sort() – Sorts indexed arrays in ascending order
  • rsort() – Sorts indexed arrays in descending order
  • asort() – Sorts associative arrays by value (ascending)
  • arsort() – Sorts associative arrays by value (descending)
  • ksort() – Sorts associative arrays by key (ascending)
  • krsort() – Sorts associative arrays by key (descending)

? Syntax / Theory

Array sorting functions directly modify the original array. Some functions reindex numeric keys, while others preserve key-value relationships. Choosing the correct function depends on whether the array is indexed or associative.

? Example 1: Using sort()

? View Code Example
// Sorting an indexed array in ascending order

? Explanation

The sort() function arranges numeric values in ascending order and resets the array indexes starting from zero.

? Example 2: Using asort()

? View Code Example
// Sorting an associative array by values while keeping keys
 25, "Jane" => 28, "Doe" => 22);
asort($ages);
print_r($ages);
?>

? Explanation

The asort() function sorts array values in ascending order while preserving their corresponding keys.

? Example 3: Using ksort()

? View Code Example
// Sorting an associative array by keys alphabetically
 25, "name" => "John", "city" => "New York");
ksort($person);
print_r($person);
?>

? Explanation

The ksort() function sorts the array based on keys in alphabetical order.

? Interactive Sorting Lab

Select a function to see how it transforms the data below.

Raw Data

 

Resulting Array

 

 

? Use Cases

  • Sorting product prices or scores
  • Arranging associative data like user profiles
  • Preparing ordered data for display

✅ Tips & Best Practices

  • Use sort() and rsort() only for indexed arrays
  • Prefer asort() or ksort() when key preservation matters
  • Use descending variants for reverse ordering

? Try It Yourself

  • Sort an array of scores using rsort()
  • Create an associative array of products and prices, then sort by price
  • Sort an array by keys using krsort()