Search code examples
phparraysstringsortingnumerical

PHP - Sort keys of an array that are different strings but contain numbers at the end


I have the following keys in my array:

Array (  
    "Danger - 69" => Array();  
    "Fab - 67" => Array();  
    "Cat - 68" => Array();  
)

I want it to be ordered by the number in the string and not the first letter in the string itself, like this:

Array (  
    "Fab - 67" => Array();  
    "Cat - 68" => Array();  
    "Danger - 69" => Array();  
)  

Solution

  • You can do it this way:

    <?php
    
    $data = array (
    "Danger - 69" => Array(),
    "Fab - 67" => Array(),
    "Cat - 68" => Array(),
    );
    
    
    uksort($data, function($a, $b) {
       $pos = strrpos($a, '-');
       if ($pos !== false) {
          $a = (int) trim(substr($a,$pos+1));
       }
       $pos = strrpos($b, '-');
       if ($pos !== false) {
          $b = (int) trim(substr($b,$pos+1));
       }
    
       return $a - $b;
    
    }); 
    
    var_dump($data);