-2

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"));
10
  • 2
    Why don't use built-in method? not_a_student is just a cover? Commented Apr 24, 2018 at 9:35
  • Why without using sort(), asort() and usort()? Commented Apr 24, 2018 at 9:35
  • @Brainfeeder Because that is what the assignment says Commented Apr 24, 2018 at 9:36
  • 3
    Maybe less weed and more attending in class is the solution :D Commented Apr 24, 2018 at 9:37
  • 3
    Possible duplicate of sorting array value without using built in php like sort() etc Commented Apr 24, 2018 at 9:42

3 Answers 3

3
// 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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

-6
$arr = array('Apple', 'Banana', 'Chips', 'Dr.Pepper'); // Create a sorted array manually
print_r($arr); // prints a manually sorted array

3 Comments

Ouch! Cutting :)
I guess this would at least earn some points for thinking out-of-the-box
Why you are not saying some words on how to think out of the box on this specific case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.