php - Laravel Collections: Shift Value *and* Key?
Do the laravel collection methods (or PHP array methods, for that matter) have a way to shift off the first key/value pair of a collection?
That is, if I have the following small program
$collection = collect(['key1'=>'value1','key2'=>'value2']);
var_dump(
$collection->first()
);
var_dump(
$collection->shift()
);
I canshift()
value1
off the beginning of the collection, or grab it without removing it viafirst()
. What I'd like is way, with one line of code, to shift off or grab the key of the first value (i.e.key1
). I know I can do something like this
$result = (function($c){
foreach($c as $key=>$value)
{
return $key;
}
})($collection);
but I was hoping-that/wondering-if Laravel had something more elegant/compact.
Answer
Solution:
Grabbing an element (fist or last):
First one
Result
Last one
Result
Grabbing first key I
Result
Grabbing first key II
Result
Answer
Solution:
One way to grab the keys is using
To get the first key, you could do:
However, since keys() will return a new collection, it's not possible to shift the values off of the original collection in one line, but you could use forget with the $key or just shift the original collection afterwards.
Answer
Solution:
Splice can work for you:
See: https://laravel.com/docs/5.4/collections#method-splice