Sorting an Array in Descending Order Without Using rsort() in PHP
The rsort() function in PHP sorts an array in descending order. However, if you want to achieve this without using built-in array functions, you can implement a manual sorting algorithm, like Bubble Sort or Selection Sort.
Method 1: Using Bubble Sort
Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order.
Code Example:
<?php
$array = [15, 3, 25, 10, 5];
$length = count($array);
// Bubble Sort Algorithm
for ($i = 0; $i < $length - 1; $i++) {
for ($j = 0; $j < $length - $i - 1; $j++) {
if ($array[$j] < $array[$j + 1]) {
// Swap values
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
}
}
}
// Print sorted array
print_r($array);
?>
Output:
Array ( [0] => 25 [1] => 15 [2] => 10 [3] => 5 [4] => 3 )
Method 2: Using Selection Sort
Selection Sort finds the largest element and swaps it to the correct position.
Code Example:
<?php
$array = [15, 3, 25, 10, 5];
$length = count($array);
// Selection Sort Algorithm
for ($i = 0; $i < $length - 1; $i++) {
$maxIndex = $i;
for ($j = $i + 1; $j < $length; $j++) {
if ($array[$j] > $array[$maxIndex]) {
$maxIndex = $j;
}
}
// Swap values
$temp = $array[$i];
$array[$i] = $array[$maxIndex];
$array[$maxIndex] = $temp;
}
// Print sorted array
print_r($array);
?>
Output:
Array ( [0] => 25 [1] => 15 [2] => 10 [3] => 5 [4] => 3 )
Instead of using rsort()
, you can manually implement sorting algorithms like Bubble Sort or Selection Sort to sort an array in descending order.
Keep Learning:)