How do you sort arrays in PHP? Explain sort, ksort, and usort. PHP में arrays कैसे sort करते हैं? sort, ksort और usort समझाएं।
Short Answer
Indexed Arrays use numeric keys (starting from 0 by default) to store and access data.
Associative Arrays use named string keys that you define to store and access data, acting like dictionaries or hash maps.
Detailed Explanation & Code Example
1. Indexed Arrays
Best used when you have a simple list of items where the order matters, but you don't need to assign specific labels to them.
$colors = ["Red", "Green", "Blue"];
// Accessing data requires knowing its numeric index
echo $colors[0]; // Outputs: Red
echo $colors[2]; // Outputs: Blue
// Adding a new item automatically assigns the next index (3)
$colors[] = "Yellow";
2. Associative Arrays
Best used when you want to map a specific key to a specific value, making the code highly readable and organized.
$user = [
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
];
// Accessing data is intuitive using the string key
echo $user["first_name"]; // Outputs: John
echo $user["age"]; // Outputs: 30
// Adding a new item
$user["role"] = "Admin";
| Function | किससे sort | Keys preserved? |
|---|---|---|
| sort() | Values, ascending | नहीं, re-indexed |
| rsort() | Values, descending | नहीं, re-indexed |
| asort() | Values, ascending | हाँ |
| ksort() | Keys, ascending | हाँ (स्वाभाविक रूप से) |
| usort() | Values, custom comparison callback से | नहीं, re-indexed |
| uasort() | Values, custom callback | हाँ |
$users = [
['name' => 'Amit', 'age' => 30],
['name' => 'Raj', 'age' => 25],
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
// age के हिसाब से ascending sort, spaceship operator सेइंटरव्यू टिप: spaceship operator <=> जानें - comparison callbacks लिखने का आधुनिक standard तरीका (-1, 0, या 1 रिटर्न करता है)।
Was this answer clear?