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 can shift()
value1
off the beginning of the collection, or grab it without removing it via first()
. 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.
Grabbing an element (fist or last):
First one
$collection->take(1);
Result
=> Illuminate\Support\Collection {#926
all: [
"key1" => "value1",
],
}
Last one
$collection->take(-1);
Result
=> Illuminate\Support\Collection {#924
all: [
"key2" => "value2",
],
}
Grabbing first key I
$collection->take(1)->keys()->first();
Result
"key1"
Grabbing first key II
key($collection->take(1)->toArray());
Result
"key1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With