PHP Array Mode Function

The following mode function will return the most commonly occurring value from an array of values, also called the mode. If just the array is used then only the most commonly occurring value will be returned. The second parameter can be used to return an array containing the mode and the number of times that this value occurs in the array.

function array_mode($array,$justMode=0) 
{
  $count = array();
  foreach ( $array as $item) {
    if ( isset($count[$item]) ) {
      $count[$item]++;
    }else{
      $count[$item] = 1;
    };
  };
  $mostcommon = '';
  $iter = 0;
  foreach ( $count as $k => $v ) {
    if ( $v > $iter ) {
    $mostcommon = $k;
    $iter = $v;
    };
  };
  if ( $justMode==0 ) {
    return $mostcommon;
  } else {
    return array("mode" => $mostcommon, "count" => $iter);
  }
}

This is used in the following way.

$array = array(1,1,0,1);
print_r(array_mode($array, 0)); // prints 1
print_r(array_mode($array, 1)); // prints Array ( [mode] => 1 [count] => 3 )

If you just wanted a list of the most commonly occurring values in an array then you could use the PHP function array_count_values(). This will return an array containing all of the values in the array and the number of times each one occurs. Here is an example of it's use.

$array = array(1, 1, 0, 1);
print_r(array_count_values($array)); // prints Array ( [1] => 3 [0] => 1 )

Comments

Thanks, I was going to write one myself, but decided to see if one was available--no sense in reinventing the wheel.

Permalink

Thanks, nice article.

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.