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

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

Laravel 5

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

public function median(
    $key = null
);

Example Use

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

// Create a collection of sample values.
$values = collect([
   100, 200, 300, 400
]);

// Create a collection of sample test scores.
$testScores = collect([
    [
        'name' => 'Alice',
        'score' => 0.96
    ],
    [
        'name' => 'Bob',
        'score' => 0.79
    ],
    [
        'name' => 'Charlie',
        'score' => 0.88
    ]
]);

// Calculate the median value.
$valuesMedian = $values->median();

// Calculate the median test score.
$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

Start the Discussion

Leave a comment

Subscribe to our newsletter