PHP Array Mode Function

7th January 2008 - 2 minutes read time

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.

  1. function array_mode($array,$justMode=0)
  2. {
  3. $count = array();
  4. foreach ( $array as $item) {
  5. if ( isset($count[$item]) ) {
  6. $count[$item]++;
  7. }else{
  8. $count[$item] = 1;
  9. };
  10. };
  11. $mostcommon = '';
  12. $iter = 0;
  13. foreach ( $count as $k => $v ) {
  14. if ( $v > $iter ) {
  15. $mostcommon = $k;
  16. $iter = $v;
  17. };
  18. };
  19. if ( $justMode==0 ) {
  20. return $mostcommon;
  21. } else {
  22. return array("mode" => $mostcommon, "count" => $iter);
  23. }
  24. }

This is used in the following way.

  1. $array = array(1,1,0,1);
  2. print_r(array_mode($array, 0)); // prints 1
  3. 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.

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

Comments

Permalink

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

JB (Sat, 04/13/2019 - 13:36)

Add new comment

The content of this field is kept private and will not be shown publicly.