Search code examples
phparrayssortingasort

How to sort an array with one exception in PHP


Let's say I have an array called $array that looks like this once I run asort on it:

Array
(
    [1] => Apples
    [2] => Bananas
    [3] => Cherries
    [4] => Donuts
    [5] => Eclairs
    [6] => Fried_Chicken
)

What is the simplest way to make it so that, after sorting alphabetically, the key that has the value "Donuts" is removed and then put at the end?


Solution

  • I came up with this. Tested it and confirmed it works. Reordered your array so I could actually see the sorting.

    $arr = Array(
      1 => "Fried_Chicken",
      2 => "Donuts",
      3 => "Bananas",
      4 => "Apples",
      5 => "Eclairs",
      6 => "Cherries"
    );  
    
    // Get donut and key
    $donut_key = array_search("Donuts", $arr);
    $donut = $arr[$donut_key];  // If you don't need to keep the value, skip this line
    
    // Remove donut
    unset($arr[$donut_key]);
    
    // Sort
    asort($arr);
    
    // Append Donut
    $arr += array($donut_key => $donut);
    

    Array Search http://php.net/manual/en/function.array-search.php

    Key preserving append http://www.vancelucas.com/blog/php-array_merge-preserving-numeric-keys/