-1

I'm trying to find the most used word in a string in PHP. The lyrics file is a string of lyrics.

            //display the most used word in the lyrics file
        $wordCount = str_word_count($lyrics);
        $wordCountArray = array();
        foreach($wordCount as $word){
            if(!array_key_exists($word, $wordCountArray)){
                $wordCountArray[$word] = 1;
            }else{
                $wordCountArray[$word] += 1;
            }
        }
        arsort($wordCountArray);
        print_r($wordCountArray[0]);

I'm getting errors with this code and I'm wondering what isn't working. I need the actual word and not the number.

2 Answers2

1

I think you meant:

$words = str_word_count($lyrics, 1)
foreach($words as $word) {
Aaron Mansheim
  • 425
  • 3
  • 11
0

Simple example

<?php
    $string = 'Hello hi hello abcd abc hoi bye hello';

    $string = strtolower($string);
    $words = explode(' ',$string);
    var_dump(array_count_values($words));