PHP: how to find the most used array key?

Let's say I have a simple 1D array with 10-20 elements. Some will be duplicated, how would I know which record is used the most? as..

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

How can I show the “test” as the most used record?

+3
source share
3 answers
$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));
+9
source

You can count the number of occurrences of each value with 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 common value, you can call max in 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"
*/

, :

$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"
}
*/
+5

Source: https://habr.com/ru/post/1740055/


All Articles