Skip to content
This repository has been archived by the owner on Jul 16, 2021. It is now read-only.

Collection::implode() with last item separator support #1109

Closed
rentalhost opened this issue Apr 10, 2018 · 2 comments
Closed

Collection::implode() with last item separator support #1109

rentalhost opened this issue Apr 10, 2018 · 2 comments

Comments

@rentalhost
Copy link

Add a third parameter to Collection::implode() to works like a last item separator ("and", "or"). It should be like Collection::implode($value, $glue = null, $lastGlue = null).

Behavior

  1. Will works only if $lastGlue is not null, else will works exactly as currently;
  2. Will works only if count($this->items) >= 2;
  3. Will get $this->last() and will implode all items except last;
  4. Will concatenate previous value with the $lastGlue and last item;

Example

$collection = new Collection([ '1', '2' ]);

$collection->implode(', ');          // string ("1, 2")
$collection->implode(', ', ' and '); // string ("1 and 2")

$collection->push('3');

$collection->implode(', ');          // string ("1, 2, 3")
$collection->implode(', ', ' and '); // string ("1, 2 and 3")

Example Macro

Currently I am working with macros, but I think that it could be done by the framework once that is an easy and very useful feature. That is my current version (it have some IDE annotations).

Collection::macro('implodeLast', function ($value, $glue = null, $lastGlue = null) {
    /** @var Collection $collection */
    $collection = $this;
    $first      = $collection->first();

    if (\is_array($first) || \is_object($first)) {
        return $collection->pluck($value)->implodeLast($glue, $lastGlue);
    }

    if ($collection->count() >= 2) {
        return $collection->slice(0, -1)->implode($value) . $glue . $collection->last();
    }

    return implode($value, $collection->all());
});

References:

@staudenmeir
Copy link

laravel/framework#27723 added the join() method with a $finalGlue parameter.

@rentalhost
Copy link
Author

rentalhost commented May 16, 2019

You are right.

Closing. Implemented and merged by laravel/framework#27723.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants