-3

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

$string[0] = "They";
$string[1] = "started";
$string[2] = "plotting";
$string[3] = "against";
$string[4] = "him";

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

$string[0] = "started";
$string[1] = "plotting";
$string[2] = "him";
$string[3] = "against";
$string[4] = "they";

3 Answers3

3

usort allows a custom sort function to be passed, so you can do:

usort($string , function($a, $b) {
  $aLastChar = substr($a, -1);
  $bLastChar = substr($b, -1);

  return ($aLastChar < $bLastChar) ? -1 : 1;
});
thelastshadow
  • 3,020
  • 3
  • 31
  • 33
0

You can invert the array value text and use sort as usual, then invert the output again.

Because you are considering the last letter of the words

$strings = [
 "They",
 "started",
 "plotting",
 "against",
 "him",
];
foreach ($strings as $key => $value) {
    $strings[$key] = strrev($value);
}
sort($strings);
foreach ($strings as $key => $value) {
    $strings[$key] = strrev($value);
}
print_r($strings);

Result:

Array
(
    [0] => started
    [1] => plotting
    [2] => him
    [3] => against
    [4] => They
)
erfan
  • 54
  • 5
0

I haven't touched php in a long time, this is not the cleanest solution. But a quick solution is using array_map to reverse all of the strings, followed by calling sort to sort the array, then reversing the array again. A more effective solution would be by writing a custom comparer so you only iterate through the array once; rather than three times.

$string[0] = "They";
$string[1] = "started";
$string[2] = "plotting";
$string[3] = "against";
$string[4] = "him";

$output = array_map('strrev', $string);
sort($output);
$sorted = array_map('strrev', $output);
var_dump($sorted);

Edit: (Cannot comment yet):

Although thelastshadow's solution has less iterations; keep in mind that it'll only compares the last character. So once you have multiples of the same characters the storting becomes incorrect.