- krsort: documentation ( source)
- explode: documentation ( source)
- natcasesort: documentation ( source)
<?php
$text = "Rocket abc bla blub bla Rocket";
$textArr = explode(" ", $text);
$wordCountArr = [];
foreach ($textArr as $word) {
if (!isset($wordCountArr[$word])) {
$wordCountArr[$word] = 1;
} else {
$wordCountArr[$word]++;
}
}
natcasesort($wordCountArr);
$textOrderArr = $wordCountArr;
$inversedArr = [];
foreach ($textOrderArr as $word => $count) {
$inversedArr[$count][] = $word;
}
krsort($inversedArr);
foreach ($inversedArr as $count => $words) {
foreach ($words as $word) {
echo $count . " x " . $word;
echo PHP_EOL;
}
}