Sorting an Array Without Using sort() in PHP
The sort() function in PHP arranges an array in ascending order. However, if you want to sort an array manually, you can implement a sorting algorithm such as Bubble Sort or Selection Sort.
Method 1: Using Bubble Sort
Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order.
Code Example:
<?php
$array = [25, 5, 15, 10, 20];
$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] => 5 [1] => 10 [2] => 15 [3] => 20 [4] => 25 )
Method 2: Using Selection Sort
Selection Sort repeatedly finds the smallest element and places it in the correct position.
Code Example:
<?php
$array = [25, 5, 15, 10, 20];
$length = count($array);
// Selection Sort Algorithm
for ($i = 0; $i < $length - 1; $i++) {
$minIndex = $i;
for ($j = $i + 1; $j < $length; $j++) {
if ($array[$j] < $array[$minIndex]) {
$minIndex = $j;
}
}
// Swap values
$temp = $array[$i];
$array[$i] = $array[$minIndex];
$array[$minIndex] = $temp;
}
// Print sorted array
print_r($array);
?>
Output:
Array ( [0] => 5 [1] => 10 [2] => 15 [3] => 20 [4] => 25 )
Instead of using sort()
, you can implement sorting algorithms like Bubble Sort or Selection Sort to arrange an array in ascending order. These methods give full control over the sorting process without relying on built-in PHP functions
Keep Learning 🙂