PHP: How to find most used array key?

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

Lets say I have a simple 1D array with 10-20 entries. Some will be duplicate, How would I find out which entry is used the most? like..

$code = Array("test" , "cat" , "test" , "this", "that", "then"); 

How would I show "test" as the most used entry?

回答1:

$code = Array("test" , "cat" , "test" , "this", "that", "then");  function array_most_common($input) {    $counted = array_count_values($input);    arsort($counted);    return(key($counted));      }  echo '<pre>'; print_r(array_most_common($code)); 


回答2:

You can get a count of the number of occurrences of each value by using array_count_values.

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); $counts = array_count_values($code); var_dump($counts); /* array(5) {   ["test"]=>   int(2)   ["cat"]=>   int(2)   ["this"]=>   int(1)   ["that"]=>   int(1)   ["then"]=>   int(1) } */ 

To get the most frequently occurring value, you can call max on the array and then access the (first) value with array_search.

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); $counts = array_count_values($code); $max = max($counts); $top = array_search($max, $counts); var_dump($max, $top); /* int(2) string(4) "test" */ 

If you wish to cater for multiple most-frequent values, then something like the following would work:

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); $counts = array_count_values($code); $max = max($counts); $top = array_keys($counts, $max); var_dump($max, $top); /* int(2) array(2) {   [0]=>   string(4) "test"   [1]=>   string(3) "cat" } */ 


回答3:

Use array_count_values



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!