Jump to content

what if i want to compare multiple strings and count the number of times a k


jjk2

Recommended Posts

what if i want to compare between multiple strings and show the count of the number of times a keyword repeats?

 

for ex)

 

apple blue green

apple yellow not

apple something blue

apple drugs car yellow

 

apple count is 4, yellow count is 2, blue count is 2.

To easy:

 

<?php
$strings = array(
    'apple blue green',
    'apple yellow not',
    'apple something blue',
    'apple drugs car yellow'
);

$wordcounts = array();
foreach ($strings as $string) {
    $words = explode(' ', $string);
    foreach ($words as $word) {
        if (isset($wordcounts[$word])) {
            ++$wordcounts[$word];
        } else {
            $wordcounts[$word] = 1;
        }
    }
}

print_r($wordcounts);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.