Search code examples
phparrayssorting

Sort an array by the last couple characters of its values?


In PHP, how might one sort an array by the last couple of characters of its values? Take, for example, the following array:

$donuts[0] = "Chocolate 02";
$donuts[1] = "Jelly 16";
$donuts[2] = "Glazed 01";
$donuts[3] = "Frosted 12";

After the sort, the array would look like this (note the order based on the last two characters of each value... also note the rewritten indexes):

$donuts[0] = "Glazed 01";
$donuts[1] = "Chocolate 02";
$donuts[2] = "Frosted 12";
$donuts[3] = "Jelly 16";

I can't seem to find a built-in function that can do this and have been racking my brain for the simplest and most efficient way to get this accomplished. Help! And thanks!


Solution

  • This should do the trick:

    header('Content-Type: Text/Plain');
    $donuts[0] = "Chocolate 02";
    $donuts[1] = "Jelly 16";
    $donuts[2] = "Glazed 01";
    $donuts[3] = "Frosted 12";
    
    print_r($donuts);
    
    usort($donuts, function ($a, $b){
        return substr($b, -2) - substr($a, -2);
    });
    
    print_r($donuts);
    

    NOTE

    1. To convert from highest to smallest:

      return substr($b, -2) - substr($a, -2);
      
    2. This answer make an assumption that the last 2 characters is to be used.

    UPDATE

    To make it work on PHP version 5.2, change the return part to:

    return substr($b, strlen($b) - 2) - substr($a, strlen($a) - 2);