find the mode of a list of numbers in php

To find the mode of a list of numbers in PHP, you can use the built-in function array_count_values to count the occurrences of each value in the array, and then use array_search to find the value with the highest count:

main.php
function calculateMode($numbers) {
    $counts = array_count_values($numbers);
    $mode = array_search(max($counts), $counts);
    return $mode;
}
148 chars
6 lines

Here, $numbers is the array of numbers that you want to find the mode of. The array_count_values function returns an associative array where the keys are the distinct values in the array, and the values are the counts of those values. The max function is used to find the highest count, and array_search is used to find the corresponding value.

You can then call this function with your array of numbers, like so:

main.php
$numbers = [1, 2, 3, 4, 4, 4, 5, 5, 6];
$mode = calculateMode($numbers);
echo "The mode of the array is: $mode";
113 chars
4 lines

This will output:

main.php
The mode of the array is: 4
28 chars
2 lines

related categories

gistlibby LogSnag