Good day!
There is a set of words. For example: "London Paris London Moscow Paris London Kiev Paris London Kiev".
It is necessary to get the result in decreasing order:
London - 4
Paris - 3
Kiev - 2
Moscow - 1

I was able to cope with the task partially (and even then not quite))):

$str = 'Лондон Париж Лондон Москва Париж Лондон Киев Париж Лондон Киев'; echo substr_count($str, 'Лондон').'<br>'; 



Tell me how to implement, if you do not know what the words will be and that the result was in decreasing order?

  • You have already asked 10 questions on the site. Most of your questions have multiple answers. No answer is marked as a solution. You really didn’t have any answers or do you not mark the answers that came up as a solution to your questions? - Visman
  • I chose the necessary answers as correct, but I clarified that I needed a reputation from 15. I haven’t got it yet (( - Tanya
  • You may need a reputation to make an answer upvote, and to mark it as Correct, no reputation is required. - teran

3 answers 3

We save with the coding UTF-8 without BOM. It is this encoding should be text.

 header('Content-Type: text/html; charset=utf-8'); $str = 'Лондон Париж Лондон Москва Париж Лондон Киев Париж Лондон Киев'; // разбиваем на слова, модификатор u используется для юникод строки $words = preg_split("/([^[:alnum:]]|['-])+/us", $str); // оставляем только уникальные слова $words = array_unique($words); $arr = array(); // считаем какие из слов сколько встречаются раз foreach($words as $word) { $arr[$word] = substr_count($str, $word); } // сортируем, оставляя ключи массива arsort($arr); // выводим foreach ($arr as $city => $count) { echo $city.' - '.$count.'<br>'; } 
     $in = 'Лондон Париж Лондон Москва Париж Лондон Киев Париж Лондон Киев'; $words = explode(' ', $in); $out = []; foreach($words as $word){ isset($out[$word])?$out[$word]++:$out[$word]=1; } arsort($out); print_r($out); 

    sandbox

      explode will divide the string into tokens, creating an array. array_count_values ​​will group the array and count the quantities. Well, array_multisort will arrange the elements in the right order.