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);
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.12 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
2 x Rocket 2 x bla 1 x abc 1 x blub
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.35, 5.6.0 - 5.6.28
2 x Rocket 2 x bla 1 x blub 1 x abc
Output for 5.2.3 - 5.2.17, 5.3.0 - 5.3.29
Parse error: syntax error, unexpected '[' in /in/egGmI on line 43
Process exited with code 255.
Output for 5.1.0 - 5.1.6, 5.2.0 - 5.2.2
<br /> <b>Parse error</b>: syntax error, unexpected '[' in <b>/in/egGmI</b> on line <b>43</b><br />
Process exited with code 255.
Output for 5.0.0 - 5.0.5
<br /> <b>Parse error</b>: parse error, unexpected '[' in <b>/in/egGmI</b> on line <b>43</b><br />
Process exited with code 255.
Output for 4.4.2 - 4.4.9
<br /> <b>Parse error</b>: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in <b>/in/egGmI</b> on line <b>10</b><br />
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
<br /> <b>Parse error</b>: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in <b>/in/egGmI</b> on line <b>10</b><br />
Process exited with code 255.
Output for 4.3.2 - 4.3.4
<br /> <b>Parse error</b>: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in <b>/in/egGmI</b> on line <b>10</b><br />
Process exited with code 255.

preferences:
253.03 ms | 401 KiB | 345 Q