Illuminate\Support\Collection::median PHP Method

median() public method

Get the median of a given key.
public median ( null $key = null ) : mixed | null
$key null
return mixed | null
    public function median($key = null)
    {
        $count = $this->count();
        if ($count == 0) {
            return;
        }
        $values = with(isset($key) ? $this->pluck($key) : $this)->sort()->values();
        $middle = (int) ($count / 2);
        if ($count % 2) {
            return $values->get($middle);
        }
        return (new static([$values->get($middle - 1), $values->get($middle)]))->average();
    }

Usage Example

 public function testMedianOnEmptyCollectionReturnsNull()
 {
     $collection = new Collection();
     $this->assertNull($collection->median());
 }