Skip to content

Commit

Permalink
[10.x] Introduce new Arr::take() helper (#50015)
Browse files Browse the repository at this point in the history
* Support/Arr: Introduce new Arr::limit() helper

* Arr: Rename limit() to take() for consistency
  • Loading branch information
ryangjchandler committed Feb 9, 2024
1 parent 24d0b5b commit 0a8c91b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit 0a8c91b

Please sign in to comment.