Find the mode of an array in PHP

For those of you who don’t remember studying statistics in math (and I barely do), the mode refers to the value that occurs most frequently in a set of data. That contrasts with the mean — what most of us call the “average” — and the median, which is the “middle” value if you sort all of the values in order.

My daughter was recently studying all of this and it brought it back to my mind. These are really not things I use often. But, as it happens, right now in my work I have a need for a PHP function that determines the mode in a set of data.

In this case, it’s not actually numbers; it’s dates. In short, I have an array of dates, and I need to know which date occurs the most often in the array. You’d think there would be a built-in PHP function for this, likely called array_mode() or else something long and completely illogical, or short and incomprehensible. But alas, there is no array_mode() function.

Fortunately, it’s pretty damn easy to write one. I found some examples on other sites, but they weren’t pithy enough for my tastes, so I rolled my own. Now you don’t have to:

function array_mode($arr) {
  $count = array();
  foreach ((array)$arr as $val) {
    if (!isset($count[$val])) { $count[$val] = 0; }
  return key($count);

Perhaps it’s excessive even to bother casting $arr as an array, but it’s a habit I picked up a long time ago and can’t seem to shake. Anyway, there you have it. (Of course, this probably breaks if $val isn’t scalar, but I’ll leave that to you to fix.)