Zunairah iqbal
Zunairah iqbal

Reputation: 11

Count number of occurences of words from one array in another array

I have two arrays: $story and $languages

Now I want to know how many times elements or values in $languages appear in $story array. This means how many times "php", "javascript", "mysql" of $languages array appeared in $story?

How can I do this in php? Can anyone help? Here are my arrays...

$story = array();
$story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
$story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
$story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

$languages = array(
  'php', 'javascript', 'mysql'  
);

Upvotes: 1

Views: 95

Answers (3)

ImmortalPC
ImmortalPC

Reputation: 1690

With 2 loops: https://ideone.com/grRBeG

$story = array();
$story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
$story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
$story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

$languages = [
    'php' => 0,
    'javascript' => 0,
    'mysql' => 0,
];

for( $i=0,$size=count($story); $i<$size; ++$i )
{
    $text = strtolower($story[$i]);
    foreach( $languages as $word => $nb )
        $languages[$word] += substr_count($text, $word);
}

var_export($languages);

Upvotes: 1

user5139444
user5139444

Reputation:

Run two foreach loops as shown below.

$finalCount = array();
foreach($story as $current)
{
      $count=0;
     foreach($languages as $language){
         if (substr_count($current,$language) !== false) {
           $count++
         }
     }
     $finalCount[$language] = $count;

}

Upvotes: 0

Madness
Madness

Reputation: 2726

I would store the totals in your $languages array. No need to check the count before adding, because adding 0 won't affect your totals.

<?
    $story = array();
    $story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
    $story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
    $story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

    $languages = array(
        'php' => 0,
        'javascript' => 0,
        'mysql' => 0
    );

    foreach ($story as $sk => $sv){
        foreach ($languages as $lk => $lv){
            $languages[$lk] += substr_count($story[$sk], $lk);
        }
    }

    print_r($languages);
?>

Upvotes: 2

Related Questions