0

I am looping through two associative array. First one is tags and second is data. I want to count matches for each tags in each data items. for example

$tags= array("japan", "china", "usa")
$data=array("something...", "something..", "something..")

I want to count how many times japan in each posts ,how many times china in each posts and how many times usa in each post. Unfortunately I am getting count result for only first tag input japan. How to correct this ??

foreach ($tags as $tag) {   
    foreach ($data as $value) {
        $count= substr_count($value,$tag);
    }   
Nayeem Azad
  • 657
  • 5
  • 20
  • Where are you creating/assigning `$data`? What is the point of `$result=array();` when you don't use `$result` anywhere? – Patrick Q Jul 23 '18 at 14:35

1 Answers1

1

Put the results in an associative array keyed by tag, and use += to increment the value for that tag.

$results = array();
foreach ($tags as $tag) {
    $results[$tag] = 0;
    foreach ($data as $value) {
        $results[$tag] += substr_count($value, $tag);
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612