diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 482bbadf0fb0..f51accf1e408 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -225,6 +225,22 @@ public static function last($array, callable $callback = null, $default = null) return static::first(array_reverse($array, true), $callback, $default); } + /** + * Take the first or last {$limit} items from an array. + * + * @param array $array + * @param int $limit + * @return array + */ + public static function take($array, $limit) + { + if ($limit < 0) { + return array_slice($array, $limit, abs($limit)); + } + + return array_slice($array, 0, $limit); + } + /** * Flatten a multi-dimensional array into a single level. * diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 083ca5bbb306..05f6b743f3e1 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -1260,4 +1260,17 @@ public function testPrependKeysWith() ], ], Arr::prependKeysWith($array, 'test.')); } + + public function testTake() + { + $array = [1, 2, 3, 4, 5, 6]; + + $this->assertEquals([ + 1, 2, 3, + ], Arr::take($array, 3)); + + $this->assertEquals([ + 4, 5, 6, + ], Arr::take($array, -3)); + } }