Sometimes in a PHP interview, you may come across the task to sort an array in PHP without using any in-built or PHP core functions like sort(), rsort(), asort(), ksort(), arsort(), etc. You can apply the below steps for sorting an array:
Here is code to sort arrays in ascending order without a built-in function:
- Take an array: $arr = array(2,5,1,7,4)
- Initialize a loop from 0 to less than total count: for($i = 0; $i < count($arr); $i++ )
- Take second loop and it will run less than 2 of total count: for($j = 0; $j < count($arr)-1; $j++)
- Compare value from next: if($arr[$j+1] < $arr[$j])
- Initialize “$temp” variable and assign value if next one is small: $temp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $temp;
- Step 4 will run till the end of the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $arr = array(2,5,1,7,4); for($i = 0; $i < count($arr); $i++ ) { for($j = 0; $j < count($arr)-1; $j++) { if($arr[$j+1] < $arr[$j]){ $temp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $temp; } } } print_r($arr); ?> |
Here is the code to sort arrays in descending order in PHP:
- follow the all above steps. Only you have to change in 4 step which is compare sign(>): if($arr[$j+1] > $arr[$j])
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $arr = array(2,5,1,7,4); for($i = 0; $i < count($arr); $i++ ) { for($j = 0; $j < count($arr)-1; $j++) { if($arr[$j+1] > $arr[$j]){ $temp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $temp; } } } print_r($arr); ?> |