Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · Arrays & String Functions
Interview question

How do you sort arrays in PHP? Explain sort, ksort, and usort. PHP में arrays कैसे sort करते हैं? sort, ksort और usort समझाएं।

Answer

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किससे sortKeys 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?