diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index d89737e62d22..0532a468bca2 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -146,15 +146,17 @@ public function average($callback = null) */ public function median($key = null) { - $count = $this->count(); + $values = (isset($key) ? $this->pluck($key) : $this) + ->filter(function ($item) { + return ! is_null($item); + })->sort()->values(); + + $count = $values->count(); if ($count == 0) { return; } - $values = (isset($key) ? $this->pluck($key) : $this) - ->sort()->values(); - $middle = (int) ($count / 2); if ($count % 2) { diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 3601dca9c062..c5d47a59dd28 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2251,6 +2251,17 @@ public function testMedianValueByKey() $this->assertEquals(2, $collection->median('foo')); } + public function testMedianOnCollectionWithNull() + { + $collection = new Collection([ + (object) ['foo' => 1], + (object) ['foo' => 2], + (object) ['foo' => 4], + (object) ['foo' => null], + ]); + $this->assertEquals(2, $collection->median('foo')); + } + public function testEvenMedianCollection() { $collection = new Collection([