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 करना सीखो।
📋 इस Article में क्या-क्या है
- Sorting Overview
- sort() और rsort()
- asort() और arsort()
- ksort() और krsort()
- usort() — Custom Sorting
- uasort() और uksort()
- Spaceship Operator <=>
- Real World Examples
- Quick Reference Table
PHP में 9 Array Sorting Functions हैं। सही function choose करना ज़रूरी है — values sort करनी हैं या keys? Keys preserve रखनी हैं? Custom order चाहिए? यह तीन सवाल decide करते हैं।
Value ↑ Ascending
Values को A-Z / 0-9 sort करता है।
Keys Reset होती हैंValue ↓ Descending
Values को Z-A / 9-0 sort करता है।
Keys Reset होती हैंValue ↑ (Keys Safe)
Values ascending, keys preserve।
Keys Preserve होती हैंValue ↓ (Keys Safe)
Values descending, keys preserve।
Keys Preserve होती हैंKey ↑ Ascending
Keys को A-Z sort करता है।
Keys by Keys sortedKey ↓ Descending
Keys को Z-A sort करता है।
Keys by Keys sortedCustom (Values)
User-defined function से sort।
Keys Reset होती हैंCustom (Keys Safe)
Custom sort, keys preserve।
Keys Preserve होती हैंCustom Keys Sort
Keys को custom function से sort।
Keys sorted by fnsort()
$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!
?>
// 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...
?>
$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
?>
// 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
?>
// Callback must return: negative, 0, or positive
// 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]
?>
$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]
?>
// 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)
?>
$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 (सबसे सस्ता)
?>
$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";
}
?>
| Function | Sort By | Order | Keys | Best Use |
|---|---|---|---|---|
| sort() | Values | Ascending | Reset 0,1,2... | Simple indexed arrays |
| rsort() | Values | Descending | Reset 0,1,2... | Leaderboard, reverse list |
| asort() | Values | Ascending | Preserved ✅ | Assoc arrays — name=>score |
| arsort() | Values | Descending | Preserved ✅ | Top scores with names |
| ksort() | Keys | Ascending | Sorted ✅ | Config, dictionary, timeline |
| krsort() | Keys | Descending | Sorted ✅ | Reverse timeline |
| usort() | Custom fn | Custom | Reset 0,1,2... | Objects, multi-field, complex |
| uasort() | Custom fn | Custom | Preserved ✅ | Custom + key-value safe |
| uksort() | Keys (custom fn) | Custom | Sorted ✅ | Custom key sorting |
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।