Skip to content

Instantly share code, notes, and snippets.

@jpmurray
Last active March 5, 2018 21:38
Show Gist options
  • Save jpmurray/f76ae0d272886ba17ae4a2990005f5b3 to your computer and use it in GitHub Desktop.
Save jpmurray/f76ae0d272886ba17ae4a2990005f5b3 to your computer and use it in GitHub Desktop.
[Laravel Collctions] insertBefore and InsertAFter
<?php
// at some point I wanted to insert stuff before/after specific item in a collection, and this was made.
// use it at your own risk.
Collection::macro('insertBefore', function ($target, $value, $new_key = null) {
if (is_int($target)) {
$this->items = array_merge(array_slice($this->items, 0, $target), [$value], array_slice($this->items, $target));
return;
}
foreach ($this->items as $key=>$old) {
if ($key===$target && is_null($new_key)) {
$new[] = $value;
} elseif ($key===$target) {
$new[$new_key] = $value;
}
$new[$key]=$old;
}
$this->items = $new;
});
Collection::macro('insertAfter', function ($target, $value, $new_key = null) {
if (is_int($target)) {
$this->items = array_merge(array_slice($this->items, 0, $target+1), [$value], array_slice($this->items, $target+1));
return;
}
foreach ($this->items as $key=>$old) {
$new[$key]=$old;
if ($key===$target && is_null($new_key)) {
$new[] = $value;
} elseif ($key===$target) {
$new[$new_key] = $value;
}
}
$this->items = $new;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment