php - Laravel Collections: Shift Value *and* Key?

618

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.

501

Answer

Solution:

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"
351

Answer

Solution:

One way to grab the keys is using

$collectionOfKeys = $collection->keys();

To get the first key, you could do:

$key = $collection->keys()->first();

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.

$collection->forget($key);
// or $collection->shift();
941

Answer

Solution:

Splice can work for you:

$collection = collect(['key1'=>'value1','key2'=>'value2']); 

$chunked = $collection->splice(0, 1);

print_r($chunked);
//Array([key1] => value1)

print_r($collection->all());
//Array ( [key2] => value2 )

See: https://laravel.com/docs/5.4/collections#method-splice

People are also looking for solutions to the problem: php - Unable to access values from multiple html checkboxes

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.