phparrayssortingassociative-array

Move array element by associative key to the beginning of an array


So far all my research has shown that this cannot be achieved without writing lengthy functions such as the solution here

Surely there is a simpler way of achieving this using the predefined PHP functions?

Just to be clear, I am trying to do the following:

$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

// Call some cool function here and return the array where the 
// the element with key 'bla2' has been shifted to the beginning like so
print_r($test);
// Prints bla2=1234, bla=>123 etc...

I have looked at using the following functions but have so far have not been able to write a solution myself.

  1. array_unshift
  2. array_merge

To Summarize

I would like to:

  1. Move an element to the beginning of an array
  2. ... whilst maintaining the associative array keys

Solution

  • This seems, funny, to me. But here ya go:

    $test = array(
        'bla' => 123,
        'bla2' => 1234,
        'bla3' => 12345
    );
    
    //store value of key we want to move
    $tmp = $test['bla2'];
    
    //now remove this from the original array
    unset($test['bla2']);
    
    //then create a new array with the requested index at the beginning
    $new = array_merge(array('bla2' => $tmp), $test);
    
    print_r($new);
    

    Output looks like:

    Array
    (
        [bla2] => 1234
        [bla] => 123
        [bla3] => 12345
    )
    

    You could turn this into a simple function that takes-in a key and an array, then outputs the newly sorted array.

    UPDATE

    I'm not sure why I didn't default to using uksort, but you can do this a bit cleaner:

    $test = array(
        'bla' => 123,
        'bla2' => 1234,
        'bla3' => 12345
    );
    
    //create a function to handle sorting by keys
    function sortStuff($a, $b) {
        if ($a === 'bla2') {
            return -1;
        }
        return 1;
    }
    
    //sort by keys using user-defined function
    uksort($test, 'sortStuff');
    
    print_r($test);
    

    This returns the same output as the code above.