Last active
March 5, 2018 21:38
-
-
Save jpmurray/f76ae0d272886ba17ae4a2990005f5b3 to your computer and use it in GitHub Desktop.
[Laravel Collctions] insertBefore and InsertAFter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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