phparrayssortingasort

asort PHP Array and keep one entry at the top


I have a PHP array

I want to sort it alphabetically and keep a precise entry at the top:

$arr = array ("Orange", "Banana", "Strawberry", "Apple", "Pear");
asort($arr);

Now this will output:

Apple, Banana, Orange, Pear, Strawberry

I want it to keep Orange as the first entry then reorder the others:

Orange, Apple, Banana, Pear, Strawberry

Thanks.


Solution

  • Get first element from array, then return it back:

    $arr = array ("Orange", "Banana", "Strawberry", "Apple", "Pear");
    
    $first = array_shift($arr);
    asort($arr);
    array_unshift($arr, $first);
    

    Update with unknown orange position:

    $arr = array ("Banana", "Orange", "Strawberry", "Apple", "Pear"); 
    // $k is index of "Orange" in array
    $k = array_search('Orange', $arr);
    // store element with founded $k in a variable 
    $orange = $arr[$k];
    // remove $k element from $arr
    // same as `unset($arr[$k]);`
    array_splice($arr, $k, 1);
    // sort 
    asort($arr);
    // add element in the beginning
    array_unshift($arr, $orange);