!empty($line)); foreach ($lines as $line) { [$a, $b] = explode(" ", $line); $list_1[] = $a; $list_2[] = $b; } $similarity_score = 0; $count_list_2 = array_count_values($list_2); foreach ($list_1 as $item) { $similarity_score += array_key_exists($item, $count_list_2) ? $count_list_2[$item] * $item : 0; } echo $similarity_score;