Skip to content
Advertisement

PHP, Sort in alphabetical with one array with Letters

I have a code that I need to sort alphabetically, not the normal alphabet, but a specified one. We can see below :

$alphabetArray = ['t','w','h','z','k','d','f','v','c','j','x','l','r','n','q','m','g','p','s','b'];

i have this array with these letters , i need sort other array by these letters, in the other array i have this :

$wordsArray = [ "jhona", "eric", "caio", "noah ];

in the normal alphabet are A B C D E F G H .. but in this exercise , i need sort like T W H Z K D F V C J X L R N Q M G P S B

anyone can help me pls, i try sort functions but idk how to do that.

Advertisement

Answer

Use Array#usort for user defined sort with a callback. Note: It’s necessary to use use to have access to $alphabetArray in the callback.

Explanation: usort takes 2 parameter: First the array for sorting and second a callback-function for comparing 2 elements of the array. For this callback I used an anonymous function with 2 parameters (I take $a and $b, but you can use here what you want). Because I needed the $alphabetArray in this function and can’t use a third parameter for this I used useto get access to this global variable inside the function.
For comparision the compiler compares allways 2 values from your array with this callback and sort them by the return-value:

  • $a < $b needs -1 (or any other negative value)

  • $a = $b needs 0

  • $a > $b needs +1 (or any other positive value)

The comparison of the 2 values goes like this:

  • Look for the first char (beginning from the left) if one value has a smaller/bigger value (by your alphabetic-order represented in the $alphabetArray).
  • If so return the needed return value -1/+1.
  • Otherwise continue with the next char.
  • If one string is shorter then the other then stop and return 0 if both values are equal.
  • Otherwise return -1/+1 so that the shorter string will be sorted before the other.

Here for playing http://sandbox.onlinephpfunctions.com/code/06c40db2ce233494df533fc5f1842d27f94ed003

$alphabetArray = ['t','w','h','z','k','d','f','v','c','j','x','l','r','n','q','m','g','p','s','b'];
$wordsArray = [ "jhona", "eric", "caio", "noah", "noaht", "caxa", "caa" ];

usort($wordsArray, function($a,$b) use($alphabetArray) {
    $len = min(strlen($a), strlen($b));
    for ($i=0; $i<$len; $i++) {
        $aa = array_search($a[$i], $alphabetArray);
        $bb = array_search($b[$i], $alphabetArray);
        if ($aa < $bb) return -1;
        elseif ($aa > $bb) return 1;
    }
    if (strlen($a)===strlen($b)) return 0;
    else return (strlen($a) - strlen($b));
});

print_r($wordsArray);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement