asort function in php
The asort() function sorts an associative array in ascending order based on its values while preserving the array’s keys. Let’s understand how we can achieve this manually by using a custom sorting algorithm.
Steps to Sort an Associative Array Without asort()
1. Create a Sample Associative Array
Let’s start with a simple array for demonstration:
Example:
function customAsort(&$array) {
// Convert the array into an array of keys and values
$keys = array_keys($array);
$values = array_values($array);
$n = count($values);
// Perform Bubble Sort on values
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($values[$j] > $values[$j + 1]) {
// Swap values
$tempValue = $values[$j];
$values[$j] = $values[$j + 1];
$values[$j + 1] = $tempValue;
// Swap keys to maintain association
$tempKey = $keys[$j];
$keys[$j] = $keys[$j + 1];
$keys[$j + 1] = $tempKey;
}
}
}
// Rebuild the sorted array
$array = array_combine($keys, $values);
}
// Sample array
$data = [
"apple" => 3,
"orange" => 1,
"banana" => 2
];
// Sort the array
customAsort($data);
// Print the sorted array
print_r($data);
Output:
Array
(
[orange] => 1
[banana] => 2
[apple] => 3
)
- Custom Sorting Logic: Bubble Sort was used for simplicity, but you can replace it with any sorting algorithm.
- Preserving Keys: To maintain the association between keys and values, we swapped both keys and values during sorting.
- Rebuilding the Array: The array_combine() function reconstructs the associative array with sorted keys and values.
Why Use Custom Sorting?
- Learning Opportunity: Building sorting algorithms manually enhances your understanding of data structures and algorithms.
- Flexibility: Custom sorting allows greater control over sorting logic, such as handling complex objects or applying specific rules.
- Restricted Environment: In scenarios where built-in functions are restricted, custom implementations are essential.
Keep Learning 🙂