3v4l.org

run code in 300+ PHP versions simultaneously
<?php $text = "Rocket abc bla blub bla Rocket"; class CountWordSimas { /* * @param string $text */ public function countWordSort($text) { $textArray = explode(" ", $text); $wordCountArray = $this->countWords($textArray); $sortedArray = $this->sortAndReverseArray($wordCountArray); $this->printWordsCount($sortedArray); } /* * Sort the array and reverse * @return array The array sorted and reversed */ protected function sortAndReverseArray($array) { natcasesort($array); $reversedArray = $this->reverseArray($array); krsort($reversedArray); return $reversedArray; } /* * Count how many time the word appear in the array * @param array $textArray * @return array */ protected function countWords($textArray) { $wordCountArray = []; foreach ($textArray as $word) { if (!isset($wordCountArray[$word])) { $wordCountArray[$word] = 1; } else { $wordCountArray[$word]++; } } return $wordCountArray; } /* * @param array $arrayToReverse * @return array The reversed array */ protected function reverseArray($arrayToReverse) { $reversedArray = []; foreach ($arrayToReverse as $key => $value) { $reversedArray[$value][] = $key; } return $reversedArray; } /* * Print the array of words with the count value * @param array $wordsCountArray */ protected function printWordsCount($wordsCountArray) { foreach ($wordsCountArray as $count => $words) { foreach ($words as $word) { echo $count . " x " . $word; echo PHP_EOL; } } } } $simas = new CountWordSimas(); $simas->countWordSort($text);

preferences:
49.54 ms | 402 KiB | 5 Q