Home  >  Article  >  Backend Development  >  PHP counts the words that appear most frequently in two data

PHP counts the words that appear most frequently in two data

angryTom
angryTomforward
2019-10-15 11:38:522043browse

This is a classic question that is often asked in interviews. It mainly tests the mastery of some unpopular functions of PHP.

Before answering this question, let’s learn two php array functions that are not commonly used.

  • 1. array_count_values ​​counts the number of values ​​in the array

  • 2. array_intersect_key finds the intersection of the keys of two arrays

Through these two functions, we can easily calculate the intersection of the two arrays What is the word that occurs most often at the same time?

The code is as follows:

<?php
$arr = array(&#39;A&#39;, &#39;B&#39;, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;);
$arr2 = array(&#39;C&#39;, &#39;B&#39;, &#39;A&#39;, &#39;D&#39;, &#39;A&#39;);
$arr_count = array_count_values($arr);
$arr2_count = array_count_values($arr2);
print_r($arr_count);
print_r($arr2_count);
$result = array_intersect_key($arr_count, $arr2_count);
print_r($result);

Running result

PHP counts the words that appear most frequently in two data

More PHP related knowledge , please visit PHP Chinese website!

The above is the detailed content of PHP counts the words that appear most frequently in two data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.80shihua.com. If there is any infringement, please contact admin@php.cn delete