So i'm attempting to create a script that is simply a replica of the "sort" pre-defined php function. Basically it takes a user input array and sorts it (So far limited numerically). I have a problem though. I'm hoping someone can point out a simple issue with the program, whatever it may be. I'm probably somewhat tired and in that mindset where nothing I do can help it anymore.
BTW: It is supposed to sort from highest number to lowest number, I realise it doesn't go through the array for each element or whatever (Main point, it won't be fully sorted, technically it just replaces neighbouring values)
PHP Code:
<?php
// sorter function kinda sorts provided array through foreach loop
function sorter(&$array)
{
for ($i = 0, $u =1; $u>=count($array)-1; $i++, $u++)
{
if ($array[$i] < $array[$u])
{
$temp = $array[i];
$array[$i] = $array[$u];
$array[$u] = $temp;
} else {
print_r ($array);
}
}
}
//Ex. array is set, than called by the "sorter" function
$set = array (0=>7, 12, 15, 8, 20, 6);
sorter($set);
echo count($set);
print_r ($set);
From my limited knowledge of php, here's what I would assume it does:
$i starts at 0, and $u at 1. these are meant to locate the first(0) and second(1) elements of the array respectively. Both are incremented each iteration of the loop. It checks if the first element is lesser to the second element, and if it is performs the swap. It will keep going up the elements untill it cannot anymore, then it should head to the else statement of the construct where it prints the information.
Say on the first run of the loop the if statement is true, and it executes the statements. Does it directly go to the next iteration? That's just another question.
I realise I could be doing this with a switch and whatnot(a million easier ways to sort an array), but my main focus for this little project is to maintain as much structure as possible at the moment. I want to know if in the future I would be able to make a program that could have the same function, but be done with a different style of code. Anway, all help is greatly appreciated
Edit: WAAAAIT. I just realised, if I'm not printing anything each iteration, than I'm constantly re-declaring variables without actually showing them? What if I just pushed the bigger number onto a separate array on each iteration of the loop? That way it would correctly organize the information!