How to sort by strings a mixed pair of string and number elements in an array with PHP

1 Answer

0 votes
$arr = [
    "Python 4", "C 9", "C++ 5", "C# 6",
    "Java 1", "PHP 7", "Go 2"
];

function extractName(string $s): string {
    $pos = strrpos($s, ' ');
    
    return substr($s, 0, $pos);
}

usort($arr, function($a, $b) {
    return extractName($a) <=> extractName($b);
});

print_r($arr);



/*
run:

Array
(
    [0] => C 9
    [1] => C# 6
    [2] => C++ 5
    [3] => Go 2
    [4] => Java 1
    [5] => PHP 7
    [6] => Python 4
)

*/

 



answered Jan 23 by avibootz

Related questions

...