phparrayssortingassociative-array

Moving array element to top in PHP


$arr = array(
    'a1'=>'1',
    'a2'=>'2'
);

I need to move the a2 to the top, as well as keep the a2 as a key how would I go on about it I can't seem to think a way without messing something up :)


Solution

  • You can achieve that this way:

    $arr = array(
        'a1'=>'1',
        'a2'=>'2'
    );
    
    end($arr);
    
    $last_key     = key($arr);
    $last_value   = array_pop($arr);
    $arr          = array_merge(array($last_key => $last_value), $arr);
    
    /*
        print_r($arr);
    
        will output (this is tested):
        Array ( [a2] => 2 [a1] => 1 )
    */