PHP Program to Sort Array in Ascending Order
Use the PHP
sort() function to sort an array in ascending order, like sort($array); which changes the original array.Examples
Input[3, 1, 2]
Output[1, 2, 3]
Input[10, 5, 8, 1]
Output[1, 5, 8, 10]
Input[]
Output[]
How to Think About It
To sort an array in PHP, you use the built-in
sort() function which rearranges the elements from smallest to largest. You just pass your array to this function, and it changes the array directly without needing to return a new one.Algorithm
1
Get the input array.2
Call the <code>sort()</code> function on the array.3
The function rearranges the array elements in ascending order.4
Print or return the sorted array.Code
php
<?php $array = [3, 1, 2]; sort($array); print_r($array); ?>
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Dry Run
Let's trace sorting the array [3, 1, 2] through the code.
1
Initial array
The array is [3, 1, 2].
2
Call sort()
sort() rearranges the array elements.
3
Sorted array
The array becomes [1, 2, 3].
| Iteration | Array State |
|---|---|
| Start | [3, 1, 2] |
| After sort | [1, 2, 3] |
Why This Works
Step 1: Using sort() function
The sort() function sorts the array in ascending order by default.
Step 2: In-place sorting
It changes the original array directly without creating a new one.
Step 3: Printing the result
Using print_r() shows the sorted array clearly.
Alternative Approaches
rsort() for descending order
php
<?php $array = [3, 1, 2]; rsort($array); print_r($array); ?>
Sorts the array in descending order instead of ascending.
asort() to maintain keys
php
<?php $array = [3 => 'c', 1 => 'a', 2 => 'b']; asort($array); print_r($array); ?>
Sorts values ascending but keeps original keys.
usort() with custom comparison
php
<?php $array = [3, 1, 2]; usort($array, fn($a, $b) => $a <=> $b); print_r($array); ?>
Allows custom sorting logic using a callback function.
Complexity: O(n log n) time, O(1) space
Time Complexity
The sort() function uses an efficient sorting algorithm like Quicksort or Heapsort, which runs in O(n log n) time for n elements.
Space Complexity
Sorting is done in-place, so it uses O(1) extra space without creating a new array.
Which Approach is Fastest?
sort() is the fastest for simple ascending order. usort() is slower due to custom comparison overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sort() | O(n log n) | O(1) | Simple ascending sort |
| rsort() | O(n log n) | O(1) | Descending order sort |
| asort() | O(n log n) | O(1) | Sort with keys preserved |
| usort() | O(n log n) | O(1) | Custom sorting logic |
Use
sort() for simple ascending sort and asort() if you want to keep the original keys.Forgetting that
sort() changes the original array and does not return a new sorted array.