Concept Flow - Array sort functions
Start with array
Choose sort function
Compare elements
Swap if needed
Repeat until sorted
Return sorted array
The array is sorted by repeatedly comparing and swapping elements until the whole array is ordered.
<?php $arr = [3, 1, 4, 2]; sort($arr); print_r($arr); ?>
| Step | Array State | Action | Explanation | Output |
|---|---|---|---|---|
| 1 | [3, 1, 4, 2] | Start sorting | Initial array before sorting | |
| 2 | [1, 3, 4, 2] | Swap 3 and 1 | 3 > 1, swap to order ascending | |
| 3 | [1, 3, 4, 2] | Compare 3 and 4 | 3 < 4, no swap | |
| 4 | [1, 3, 2, 4] | Swap 4 and 2 | 4 > 2, swap to order ascending | |
| 5 | [1, 2, 3, 4] | Swap 3 and 2 | 3 > 2, swap to order ascending | |
| 6 | [1, 2, 3, 4] | Array sorted | No more swaps needed | [1, 2, 3, 4] |
| Variable | Start | After Step 2 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|
| arr | [3, 1, 4, 2] | [1, 3, 4, 2] | [1, 3, 2, 4] | [1, 2, 3, 4] | [1, 2, 3, 4] |
PHP array sort functions: - Use sort() to sort arrays ascending. - sort() changes the original array. - Elements are compared and swapped until sorted. - Output is the sorted array. - Works with numbers and strings.
asort() sorts values but keeps the original keys unchanged.sort() resets keys, rsort() sorts in reverse but resets keys, ksort() sorts by keys, not values.sort() sorts array values in ascending order and resets keys.asort() keeps keys, ksort() sorts by keys, arsort() sorts descending.$arr = [3 => 'apple', 1 => 'banana', 2 => 'cherry']; sort($arr); print_r($arr);
sort() sorts values ascending and resets keys starting from 0.$arr = ['b' => 2, 'a' => 1, 'c' => 3]; ksort($arr, SORT_DESC); print_r($arr);
ksort() sorts array by keys in ascending order only; it does not support descending order.SORT_DESC is invalid for ksort(); to sort keys descending, use krsort() instead.$scores = [101 => 50, 102 => 75, 103 => 50, 104 => 90];You want to sort the array by scores in descending order but keep the user IDs as keys. Which function should you use?
arsort() sorts array by values in descending order and keeps keys intact.rsort() sorts values descending but resets keys, krsort() sorts keys descending, sort() sorts ascending and resets keys.Pass the test and this pattern moves unknown