Laravel 5 Collections: Calculating the Median Value of a Collection With median

April 22, 2018 —John Koster

In mathematics, the median value is the numeric value that separates the higher half a data sample from the lower half; the median value does not necessarily exist within the data set itself. The median method can be used to get the median value of the collection; a $key may be specified to limit the calculation to nested property values.

#Signature

1public function median(
2 $key = null
3);

#Example Use

The following example demonstrates both ways to invoke the median method on a collection:

1// Create a collection of sample values.
2$values = collect([
3 100, 200, 300, 400
4]);
5 
6// Create a collection of sample test scores.
7$testScores = collect([
8 [
9 'name' => 'Alice',
10 'score' => 0.96
11 ],
12 [
13 'name' => 'Bob',
14 'score' => 0.79
15 ],
16 [
17 'name' => 'Charlie',
18 'score' => 0.88
19 ]
20]);
21 
22// Calculate the median value.
23$valuesMedian = $values->median();
24 
25// Calculate the median test score.
26$scoresMedian = $testScores->median('score');

After the above code has executed, our local variables would contain the following values:

Variable Value
$valuesMedian 250
$scoresMedian 0.88

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.