Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,3 +479,20 @@ $joined = $collection->implode(', ', function (User $user): string {
return $user->name();
});
```

### Chunk
The `chunk()` method will take your collection and return it split into
chunks (max size of `$limit`) and by default will preserve the keys
```php
$collection = new Collection(['a', 'b', 'c', 'd', 'e']);
$chunks = $collection->chunk(2);
// $chunks is now: new Collection([[0 => 'a', 1 => 'b'], [2 => 'c', 3 => 'd'], [4 => 'e']]);
```

### Keys
The `keys()` method will take your collection and return the keys of each
of the items within it
```php
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]);
$keys = $collection->keys(); // ['a', 'b', 'c', 'd', 'e']
```
22 changes: 22 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,28 @@ public function implode($glue = '', callable $callable = null): string
return implode($glue, $array);
}

/**
* Chunks a collection into a new collection where each item contains max `$limit` number of items from the original
*
* @param int $limit
* @param bool $preserveKeys
* @return Collection
*/
public function chunk(int $limit, bool $preserveKeys = true): self
{
return new Collection(array_chunk($this->getArrayCopy(), $limit, $preserveKeys));
}

/**
* Returns the keys of the collection
*
* @return array
*/
public function keys(): array
{
return array_keys($this->getArrayCopy());
}

/**
* Get a New Instance of the Same Type
*
Expand Down
22 changes: 22 additions & 0 deletions tests/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,28 @@ public function foo(): string {
);
}

/** @test */
public function itChunksTheCollection(): void
{
$collection = new Collection(['a', 'b', 'c', 'd', 'e']);
$chunks = $collection->chunk(2);

$expectedChunks = new Collection([[0 => 'a', 1 => 'b'], [2 => 'c', 3 => 'd'], [4 => 'e']]);

$this->assertEquals($expectedChunks, $chunks);
}

/** @test */
public function itReturnsTheArrayKeysOfTheCollection(): void
{
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]);
$keys = $collection->keys();

$expectedKeys = ['a', 'b', 'c', 'd', 'e'];

$this->assertEquals($expectedKeys, $keys);
}




Expand Down