Skip to content
Merged
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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,8 +464,18 @@ have its elements in the same order for a given original collection and seed
value. It will never return a different order for this combination.

### Implode
The `implode()` method will take your collection and return a string with the items joined together with `$glue`
The `implode()` method will take your collection and return a string with the
items joined together with `$glue`
```php
$collection = new Collection(['a', 'b']);
$joined = $collection->implode(', '); // 'a, b'
```

You may also pass an optional callable as the second argument which allows you
to pick the specific properties from your collected objects when imploding:
```php
$collection = new Collection($users);
$joined = $collection->implode(', ', function (User $user): string {
return $user->name();
});
```
6 changes: 4 additions & 2 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -421,11 +421,13 @@ public function shuffle(int $seed = null): self
* Join collection elements together with a string
*
* @param string $glue
* @param callable $callable
* @return static
*/
public function implode($glue = ""): string
public function implode($glue = "", callable $callable = null): string
{
return implode($glue, $this->getArrayCopy());
$data = $callable ? $this->map($callable)->getArrayCopy() : $this->getArrayCopy();
return implode($glue, $data);
}

/**
Expand Down
27 changes: 27 additions & 0 deletions tests/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,33 @@ public function itImplodesStrings(): void
$this->assertSame('a, b', $collection->implode(', '));
}

/** @test */
public function itImplodesObjects(): void
{
$newClass = function(string $foo) {
return new class($foo) {
private $foo;
public function __construct(string $foo) {
$this->foo = $foo;
}
public function foo(): string {
return $this->foo;
}
};
};
$collection = new Collection([
$newClass('foo'),
$newClass('bar'),
$newClass('baz')
]);
$this->assertSame(
'foo, bar, baz',
$collection->implode(', ', function ($item) {
return $item->foo();
})
);
}




Expand Down