How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in PHP

1 Answer

0 votes
/*
    We want to sort characters in this strict order:
    1. lowercase letters   (a–z)
    2. uppercase letters   (A–Z)
    3. odd digits          (1,3,5,7,9)
    4. even digits         (0,2,4,6,8)

    Strategy:
    ---------
    Assign each character a "category rank" and sort by:
        (category rank, natural character order)

    PHP's usort() with a custom comparator is the idiomatic way
    to implement custom sorting.
*/

/// Returns category rank for sorting.
/// Lower rank = comes earlier.
function category(string $c): int {
    if (ctype_lower($c)) return 0;   // lowercase
    if (ctype_upper($c)) return 1;   // uppercase

    if (ctype_digit($c)) {
        $d = intval($c);
        return ($d % 2 === 1) ? 2 : 3;   // odd digits → 2, even digits → 3
    }

    return 4; // fallback (should not happen for alphanumeric input)
}

/// Custom comparator for sorting characters
function compareChars(string $a, string $b): int {
    $ca = category($a);
    $cb = category($b);

    if ($ca !== $cb)
        return $ca <=> $cb;   // sort by category first

    return $a <=> $b;         // tie-breaker: natural order
}

$s = "a2B3cD8f1Z0";

// Convert string to array of characters
$arr = str_split($s);

// Sort using custom comparator
usort($arr, 'compareChars');

// Rebuild sorted string
$result = implode('', $arr);

echo "Sorted result: $result\n";


/*
run:

Sorted result: acfBDZ13028

*/

 



answered Jul 14 by avibootz

Related questions

...