How to sort an array in ascending order?


In this tutorial we will learn how to sort an array ascending order. Most of the programming languages provide inbuilt functions for sorting or more. But we will not be using that inbuilt method we will use core method or logic for that.

function sortAnArrayFunction($my_array)
{
    for ($i = 0; $i < count($my_array); $i++) {
        $val = $my_array[$i];
        $j = $i - 1;
        while ($j >= 0 && $my_array[$j] > $val) {
            $my_array[$j + 1] = $my_array[$j];
            $j--;
        }
        $my_array[$j + 1] = $val;
    }
    return $my_array;
}
$test_array = [15, 10, 20, -5, -1, 4, 1];

echo 'Original Array :';
print_r($test_array);

echo 'Sorted Array :';
print_r(sortAnArrayFunction($test_array));
Original Array :Array
(
[0] => 15
[1] => 10
[2] => 20
[3] => -5
[4] => -1
[5] => 4
[6] => 1
)
Sorted Array :Array
(
[0] => -5
[1] => -1
[2] => 1
[3] => 4
[4] => 10
[5] => 15
[6] => 20
)