PHP Arrays · Chapter 8.3 · Sorting Functions

PHP Array Sorting Functions
sort · rsort · asort · usort · ksort

PHP Array Sorting की पूरी जानकारी — 9 Sorting Functions, Spaceship Operator, Custom Sorting, Real World Examples। Numbers, Strings, Objects — सब sort करना सीखो।

↑ sort/asort/ksort ↓ rsort/arsort/krsort ⚙️ usort/uasort/uksort 🚀 Spaceship <=> ⏱️ 10 min read
9Sorting Functions
<=>Spaceship Operator
trueSort — original modify
asortKeys preserve करे

📋 इस Article में क्या-क्या है

  1. Sorting Overview
  2. sort() और rsort()
  3. asort() और arsort()
  4. ksort() और krsort()
  5. usort() — Custom Sorting
  6. uasort() और uksort()
  7. Spaceship Operator <=>
  8. Real World Examples
  9. Quick Reference Table
1
Sorting Overview — कौन सा Function कब?

PHP में 9 Array Sorting Functions हैं। सही function choose करना ज़रूरी है — values sort करनी हैं या keys? Keys preserve रखनी हैं? Custom order चाहिए? यह तीन सवाल decide करते हैं।

sort()
Value ↑ Ascending

Values को A-Z / 0-9 sort करता है।

Keys Reset होती हैं
rsort()
Value ↓ Descending

Values को Z-A / 9-0 sort करता है।

Keys Reset होती हैं
asort()
Value ↑ (Keys Safe)

Values ascending, keys preserve।

Keys Preserve होती हैं
arsort()
Value ↓ (Keys Safe)

Values descending, keys preserve।

Keys Preserve होती हैं
ksort()
Key ↑ Ascending

Keys को A-Z sort करता है।

Keys by Keys sorted
krsort()
Key ↓ Descending

Keys को Z-A sort करता है।

Keys by Keys sorted
usort()
Custom (Values)

User-defined function से sort।

Keys Reset होती हैं
uasort()
Custom (Keys Safe)

Custom sort, keys preserve।

Keys Preserve होती हैं
uksort()
Custom Keys Sort

Keys को custom function से sort।

Keys sorted by fn
Key Question: Values sort? → sort/asort/usort। Keys sort? → ksort/uksort। Keys preserve चाहिए? → asort/arsort/uasort।

2
sort() और rsort() — Basic Sorting
sort
()

sort() / rsort()

sort() — Ascending (A→Z, 0→9)। rsort() — Descending (Z→A, 9→0)। दोनों numeric keys reset करते हैं। Original array modify होता है।

PHP 4+ Keys Reset! Returns: bool
Before
5
2
8
1
9

sort()
After
1
2
5
8
9
sort() और rsort() — EXAMPLES
<?php
$nums = [5, 2, 8, 1, 9, 3];

// sort — Ascending
sort($nums);
print_r($nums); // [1, 2, 3, 5, 8, 9]

// rsort — Descending
rsort($nums);
print_r($nums); // [9, 8, 5, 3, 2, 1]

// Strings sort
$fruits = ["Mango", "Apple", "Banana", "Cherry"];
sort($fruits);
print_r($fruits); // [Apple, Banana, Cherry, Mango]

// Mixed types — sort handles automatically
$mixed = [10, "Apple", 5, "Banana"];
sort($mixed);
print_r($mixed); // [5, 10, Apple, Banana]

// Keys reset हो जाती हैं!
$arr = [3 => "C", 1 => "A", 2 => "B"];
sort($arr);
print_r($arr); // [0=>"A", 1=>"B", 2=>"C"] — keys reset!
?>
sort() REAL WORLD — Leaderboard
<?php
// Students scores — top scorer पहले
$scores = [85, 92, 78, 95, 88];
rsort($scores); // Descending — highest first

foreach ($scores as $rank => $score) {
  echo "Rank " . ($rank + 1) . ": $score\n";
}
// Rank 1: 95, Rank 2: 92, Rank 3: 88...
?>

3
asort() और arsort() — Keys Preserve करके Sort
asrt
()

asort() / arsort()

Values sort करते हैं लेकिन key-value relationships preserve रहती हैं। Associative arrays के लिए ज़रूरी — जहाँ key का meaning है।

PHP 4+ Keys Preserved! Associative Arrays
asort() vs sort() — KEY DIFFERENCE
<?php
$scores = ["Rahul" => 85, "Priya" => 92, "Amit" => 78];

// sort() — keys destroy हो जाती हैं ❌
sort($scores);
print_r($scores); // [0=>78, 1=>85, 2=>92] — naam गया!

// asort() — keys safe रहती हैं ✅
$scores = ["Rahul" => 85, "Priya" => 92, "Amit" => 78];
asort($scores);
print_r($scores);
// ["Amit"=>78, "Rahul"=>85, "Priya"=>92] ✅

// arsort() — Descending, keys safe
arsort($scores);
print_r($scores);
// ["Priya"=>92, "Rahul"=>85, "Amit"=>78]

// Loop करना
arsort($scores); // Top scorer first
$rank = 1;
foreach ($scores as $naam => $score) {
  echo "#$rank $naam: $score\n";
  $rank++;
}
// #1 Priya: 92, #2 Rahul: 85, #3 Amit: 78
?>
Rule: Associative array (string keys) sort करते समय हमेशा asort/arsort use करो — sort/rsort use करने से keys destroy हो जाती हैं और data का meaning खो जाता है।

4
ksort() और krsort() — Keys के हिसाब से Sort
ksor
t()

ksort() / krsort()

Keys के आधार पर array sort करता है। Values sort नहीं होतीं — keys sort होती हैं और values साथ follow करती हैं।

PHP 4+ Sorts by Keys Config/Dictionary
ksort() और krsort() — EXAMPLES
<?php
// ksort — Keys Ascending
$config = [
  "timezone" => "Asia/Kolkata",
  "database" => "mysql",
  "app_name" => "HindiNotes",
  "version" => "2.0",
];
ksort($config);
print_r($config);
// app_name, database, timezone, version (alphabetical)

// krsort — Keys Descending
krsort($config);
print_r($config);
// version, timezone, database, app_name

// Numeric keys sort
$timeline = [
  2020 => "PHP 8.0",
  2015 => "PHP 7.0",
  2022 => "PHP 8.2",
  2004 => "PHP 5.0",
];
ksort($timeline);
foreach ($timeline as $year => $version) {
  echo "$year: $version\n";
}
// 2004: PHP 5.0, 2015: PHP 7.0, 2020: PHP 8.0, 2022: PHP 8.2
?>

5
usort() — Custom Sorting Function
usor
t()

usort()

User-defined callback से sort करता है। Complex objects, multiple fields, custom order — जब built-in sorting काफी नहीं। Spaceship operator <=> के साथ बहुत powerful।

PHP 4+ Keys Reset! Most Powerful
bool usort( array &$array, callable $callback )
// Callback must return: negative, 0, or positive
usort() — CALLBACK RULES
<?php
// Callback ($a, $b) को compare करता है:
// Negative → $a पहले आएगा
// 0 → order same रहेगा
// Positive → $b पहले आएगा

$nums = [5, 2, 8, 1];

// Old style — manual comparison
usort($nums, function($a, $b) {
  if ($a == $b) return 0;
  return ($a < $b) ? -1 : 1;
});

// Modern — Spaceship operator (much cleaner!)
usort($nums, fn($a, $b) => $a <=> $b); // Ascending
usort($nums, fn($a, $b) => $b <=> $a); // Descending (swap!)
print_r($nums); // [8, 5, 2, 1]
?>
usort() — REAL WORLD: Products, Students, Events
<?php
$products = [
  ["name" => "Laravel", "price" => 799, "rating" => 4.8],
  ["name" => "PHP Book", "price" => 450, "rating" => 4.5],
  ["name" => "MySQL", "price" => 299, "rating" => 4.2],
  ["name" => "HTML/CSS", "price" => 199, "rating" => 4.7],
];

// 1. Price ascending (सबसे सस्ता पहले)
usort($products, fn($a, $b) => $a["price"] <=> $b["price"]);
echo "Cheapest: " . $products[0]["name"]; // HTML/CSS

// 2. Rating descending (highest rated पहले)
usort($products, fn($a, $b) => $b["rating"] <=> $a["rating"]);
echo "Best Rated: " . $products[0]["name"]; // Laravel

// 3. Multi-field sort — rating desc, फिर price asc
usort($products, function($a, $b) {
  if ($a["rating"] !== $b["rating"]) {
    return $b["rating"] <=> $a["rating"]; // rating desc
  }
  return $a["price"] <=> $b["price"]; // price asc
});

// 4. String length से sort
$words = ["banana", "apple", "kiwi", "mango"];
usort($words, fn($a, $b) => strlen($a) <=> strlen($b));
print_r($words); // [kiwi, apple, mango, banana]
?>

6
uasort() और uksort() — Custom + Keys Safe
uauk
sort

uasort() / uksort()

uasort() — usort की तरह लेकिन key-value associations preserve। uksort() — Keys को custom function से sort करता है।

PHP 4+ Keys Preserved (uasort) Keys Sorted (uksort)
uasort() और uksort() — EXAMPLES
<?php
// uasort — custom sort, keys preserve
$scores = ["Rahul" => 85, "Priya" => 92, "Amit" => 78];
uasort($scores, fn($a, $b) => $b <=> $a); // Descending
print_r($scores);
// Priya=>92, Rahul=>85, Amit=>78 (keys safe!)

// uksort — keys को custom sort
$menu = [
  "Home" => "/",
  "About" => "/about",
  "Products" => "/products",
  "Contact" => "/contact",
];
// Key length से sort
uksort($menu, fn($a, $b) => strlen($a) <=> strlen($b));
print_r($menu);
// Home(/), About(/about), Contact(/contact), Products(/products)
?>

7
Spaceship Operator <=> — Sorting का Best Friend
<=>
PHP7

Spaceship Operator <=>

PHP 7 में आया — दो values compare करके -1, 0, या 1 return करता है। usort callbacks में manual if-else की जगह एक clean expression।

PHP 7+ -1 / 0 / 1 usort का साथी
5 <=> 3 1 left बड़ा है → $b पहले जाएगा
3 <=> 5 -1 left छोटा है → $a पहले जाएगा
5 <=> 5 0 equal → order same
"a" <=> "b" -1 strings भी work करता है
[1,2] <=> [1,3] -1 arrays भी compare होते हैं
SPACESHIP — Ascending vs Descending Trick
<?php
$arr = [5, 2, 8, 1, 9];

// Ascending — $a <=> $b
usort($arr, fn($a, $b) => $a <=> $b);
print_r($arr); // [1, 2, 5, 8, 9]

// Descending — $b <=> $a (swap करो!)
usort($arr, fn($a, $b) => $b <=> $a);
print_r($arr); // [9, 8, 5, 2, 1]

// Nested field sort — price
$products = [
  ["name" => "Book", "price" => 450],
  ["name" => "Pen", "price" => 50],
  ["name" => "Bag", "price" => 800],
];
usort($products, fn($a, $b) => $a["price"] <=> $b["price"]);
echo $products[0]["name"]; // Pen (सबसे सस्ता)
?>
💡 Descending Trick: $a <=> $b = Ascending। $b <=> $a = Descending (बस $a और $b swap करो!)। यह सबसे clean way है।

8
Real World — E-Commerce Sorting
E-COMMERCE — Multiple Sort Options
<?php
$products = [
  ["id" => 1, "name" => "PHP Book", "price" => 450, "rating" => 4.5, "sold" => 1200],
  ["id" => 2, "name" => "Laravel Guide", "price" => 799, "rating" => 4.8, "sold" => 890],
  ["id" => 3, "name" => "MySQL Notes", "price" => 299, "rating" => 4.2, "sold" => 2100],
  ["id" => 4, "name" => "HTML/CSS", "price" => 199, "rating" => 4.7, "sold" => 3400],
];

$sortBy = $_GET["sort"] ?? "popular";

match($sortBy) {
  "price_low" => usort($products, fn($a,$b) => $a["price"] <=> $b["price"]),
  "price_high" => usort($products, fn($a,$b) => $b["price"] <=> $a["price"]),
  "rating" => usort($products, fn($a,$b) => $b["rating"] <=> $a["rating"]),
  "popular" => usort($products, fn($a,$b) => $b["sold"] <=> $a["sold"]),
  "name" => usort($products, fn($a,$b) => $a["name"] <=> $b["name"]),
  default => null
};

foreach ($products as $p) {
  echo "{$p['name']} — ₹{$p['price']}{$p['rating']}\n";
}
?>
✅ Clean Pattern: match expression + usort + spaceship operator — तीनों मिलकर flexible और readable sorting system बनाते हैं। यही pattern real e-commerce sites में use होता है।

9
Quick Reference — सभी 9 Sorting Functions
FunctionSort ByOrderKeysBest Use
sort()ValuesAscendingReset 0,1,2...Simple indexed arrays
rsort()ValuesDescendingReset 0,1,2...Leaderboard, reverse list
asort()ValuesAscendingPreserved ✅Assoc arrays — name=>score
arsort()ValuesDescendingPreserved ✅Top scores with names
ksort()KeysAscendingSorted ✅Config, dictionary, timeline
krsort()KeysDescendingSorted ✅Reverse timeline
usort()Custom fnCustomReset 0,1,2...Objects, multi-field, complex
uasort()Custom fnCustomPreserved ✅Custom + key-value safe
uksort()Keys (custom fn)CustomSorted ✅Custom key sorting
Shortcut: "a" prefix = Keys Preserve। "k" prefix = Sort by Keys। "u" prefix = Custom callback।

निष्कर्ष

Array Sorting PHP का एक core skill है। सही function choose करना — values या keys, ascending या descending, keys preserve या reset — यही सीखना है।

sort/rsort — Simple indexed arrays। Keys reset होती हैं।

asort/arsort — Associative arrays। Keys preserve — नाम के साथ score।

ksort/krsort — Keys के हिसाब से। Config, timeline, dictionary।

usort + spaceship <=> — सबसे powerful combination। Objects और multi-field sorting।

$a <=> $b = Ascending, $b <=> $a = Descending — यह golden rule याद रखो।

"a" prefix = keys safe, "k" prefix = sort keys, "u" prefix = custom।

🚀 Chapter 8 Complete! Arrays पूरा हो गया — Overview, Functions (8.1), Functional (8.2), Sorting (8.3)। अब अगला बड़ा topic: Chapter 9: PHP Loops — for, while, foreach, do-while सब detail में।