Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 820
Alan Storm Avatar asked Dec 18 '22 05:12

Alan Storm


1 Answers

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"
like image 158
Axalix Avatar answered Jan 03 '23 22:01

Axalix