How to Compute the Modes of an Array in PHP?


The Mode of an array (numbers, strings or any other types) is the most frequently one. For example, for integer array [1, 1, 2, 0, 3], the mode is 1 (appears twice). There can be multiple modes if more than one number appears the most in the array. For example, array [1, 1, 2, 2, 0], the modes are 1 and 2 because both appear twice.

The following PHP function computes the modes and return them as a array. You can pass numbers (float and integers) and string types to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function modes_of_array($arr) {
  $values = array();
  foreach ($arr as $v) {
    if (isset($values[$v])) {
      $values[$v] ++;
    } else {
      $values[$v] = 1;  // counter of appearance
    }
  } 
  arsort($values);  // sort the array by values, in non-ascending order.
  $modes = array();
  $x = $values[key($values)]; // get the most appeared counter
  reset($values); 
  foreach ($values as $key => $v) {
    if ($v == $x) {   // if there are multiple 'most'
      $modes[] = $key;  // push to the modes array
    } else {
      break;
    }
  } 
  return $modes;
}
function modes_of_array($arr) {
  $values = array();
  foreach ($arr as $v) {
    if (isset($values[$v])) {
      $values[$v] ++;
    } else {
      $values[$v] = 1;  // counter of appearance
    }
  } 
  arsort($values);  // sort the array by values, in non-ascending order.
  $modes = array();
  $x = $values[key($values)]; // get the most appeared counter
  reset($values); 
  foreach ($values as $key => $v) {
    if ($v == $x) {   // if there are multiple 'most'
      $modes[] = $key;  // push to the modes array
    } else {
      break;
    }
  } 
  return $modes;
}

Let’s see some examples:

1
2
3
print_r(modes_of_array([1, 1, 2, 3, 4]));
print_r(modes_of_array([1.0, 1.0, 2.0, 2.0, 3, 4]));
print_r(modes_of_array(["a", "a", "b", 1, 2, 3, 1]));
print_r(modes_of_array([1, 1, 2, 3, 4]));
print_r(modes_of_array([1.0, 1.0, 2.0, 2.0, 3, 4]));
print_r(modes_of_array(["a", "a", "b", 1, 2, 3, 1]));

The results are:

Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [1] => 2
)
Array
(
    [0] => a
    [1] => 1
)

This PHP script works pretty well in computing multiple modes for array and it supports types of integers, floats, and even strings.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
304 words
Last Post: The Average, Median, STD of SteemIt Wechat Group
Next Post: Hide SteemIt Payout

The Permanent URL is: How to Compute the Modes of an Array in PHP? (AMP Version)

Leave a Reply