Search code examples
phparrayssortingksort

Sorting PHP array without ksort


I am trying to manually sort a PHP array without making use of ksort.

This is how my code looks at the moment:

function my_ksort(&$arg){
    foreach($arg as $key1 => $value1){
      foreach($arg as $key2 => $value2){
        if($key1 > $key2){
          $aux = $value2;
          $arg[$key2] = $value1;
          $arg[$key1] = $aux;
        }
      }
    }
}

It doesn't sort, I can't figure out how to make it sort.


Solution

  • You could try this:

    function my_ksort(&$arg)
        {
        $keys=array_keys($arg);
        sort($keys);
        foreach($keys as $key)
            {
            $val=$arg[$key];
            unset($arg[$key]);
            $arg[$key]=$val;
            }
        }
    

    I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.

    I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, @crypticous's algorithm does just that!