-3

How to sort an array with a function manually in alphabetical order?

Without using automatic sort such as (sort, asort, usort, ...)

I've tried the code below so far but I feel like there is another way to do it

<?php 

function sort_arrays(array $var) {
    for ($i=0; $i < 4; $i++) { 
        print_r($var);
    }
    else {
        return null;
    }
}

sort_arrays($array = array("A_first","D_last","B_second","C_third"));
not_a_student
  • 31
  • 1
  • 1
  • 5

3 Answers3

2
// take an array with some elements
$array = array('a','z','c','b');
// get the size of array
$count = count($array);
echo "<pre>";
// Print array elements before sorting
print_r($array);
for ($i = 0; $i < $count; $i++) {
    for ($j = $i + 1; $j < $count; $j++) {
        if ($array[$i] > $array[$j]) {
            $temp = $array[$i];
            $array[$i] = $array[$j];
            $array[$j] = $temp;
        }
    }
}
echo "Sorted Array:" . "<br/>";
print_r($array);
Null Pointer
  • 458
  • 1
  • 4
  • 14
1
$arr = ['c','a','d','b'];
$size =count($arr);

for($i=0; $i<$size; $i++){
        /* 
         * Place currently selected element array[i]
         * to its correct place.
         */
        for($j=$i+1; $j<$size; $j++)
        {
            /* 
             * Swap if currently selected array element
             * is not at its correct position.
             */
            if($arr[$i] > $arr[$j])
            {
                $temp     = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j] = $temp;
            }
        }
}
print_r($arr);
Rafiqul Islam
  • 1,636
  • 1
  • 12
  • 25
-5
$arr = array('Apple', 'Banana', 'Chips', 'Dr.Pepper'); // Create a sorted array manually
print_r($arr); // prints a manually sorted array
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37