Sorting Arrays

Order array elements alphabetically or numerically.

Syntaxsort($array);

PHP can sort arrays in place:

  • sort() — ascending, re-indexes keys.
  • rsort() — descending.
  • asort() / arsort() — sort by value, keep keys.
  • ksort() / krsort() — sort by key.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Sort a list of product names alphabetically with sort() for display in a dropdown menu.
  • Order an array of user records by score descending with usort() for a leaderboard.
  • Sort an associative settings array by key with ksort() for consistent config output.

More examples

sort and rsort

sort() orders ascending and reassigns numeric keys; rsort() orders descending — both operate in place.

Example · php
<?php
$names = ['Charlie', 'Alice', 'Bob'];
sort($names);
print_r($names); // Alice, Bob, Charlie

$scores = [88, 45, 97, 62];
rsort($scores);
print_r($scores); // 97, 88, 62, 45

asort and ksort preserve keys

asort() sorts by value and maintains key-value pairing; ksort() sorts by key — both essential for associative arrays.

Example · php
<?php
$prices = ['widget' => 9.99, 'gadget' => 4.49, 'tool' => 14.0];
asort($prices);
print_r($prices);
// gadget => 4.49, widget => 9.99, tool => 14.0

ksort($prices); // sort by key alphabetically

usort with a custom comparator

usort() accepts any comparator callback; reversing the spaceship operands produces descending order.

Example · php
<?php
$products = [
    ['name' => 'Gadget', 'price' => 4.49],
    ['name' => 'Widget', 'price' => 9.99],
    ['name' => 'Tool',   'price' => 14.0],
];

usort($products, fn($a, $b) => $b['price'] <=> $a['price']);

foreach ($products as $p) {
    echo "{$p['name']}: {$p['price']}\n";
}

Discussion

  • Be the first to comment on this lesson.