Search code examples
phparrayswords

how to compare n multiple sentences which are in array and get the common words using php using array_intersect and store the common words in an array


Hi friends am trying to compare n sentences in an array and get the common words which are present in more than one sentence. Here is sample

 $cars=("hello how","hello when","when you came",........,n sentences);

array_intersect is used to compare 2 or 3 arrays which have exactly common words in all the three can anyone help me with these


Solution

  • $cars = array_filter(
                array_count_values(
                       array_merge(
                            ...array_map(
                                  function($x) { return array_unique(explode(' ', $x));},
                                  $cars))), 
                function($x) { return $x > 1; });
    print_r($cars); 
    

    Step by step

    1. Explode strings and save only unique words
    2. Merge all arrays
    3. Count frequency for each word
    4. Get words that exist more than one time

    demo