Skip to content

Commit 3924fba

Browse files
[9.x] Adds collection key first/last. (#41450)
* Adds key first/last. * Update Collection.php * Update Collection.php Co-authored-by: Taylor Otwell <[email protected]>
1 parent 60c5fc7 commit 3924fba

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,16 @@ public function first(callable $callback = null, $default = null)
389389
return Arr::first($this->items, $callback, $default);
390390
}
391391

392+
/**
393+
* Get the first key of the collection.
394+
*
395+
* @return mixed
396+
*/
397+
public function firstKey()
398+
{
399+
return array_key_first($this->items);
400+
}
401+
392402
/**
393403
* Get a flattened array of the items in the collection.
394404
*
@@ -694,6 +704,16 @@ public function last(callable $callback = null, $default = null)
694704
return Arr::last($this->items, $callback, $default);
695705
}
696706

707+
/**
708+
* Get the last key of the collection.
709+
*
710+
* @return mixed
711+
*/
712+
public function lastKey()
713+
{
714+
return array_key_last($this->items);
715+
}
716+
697717
/**
698718
* Get the values of a given key.
699719
*

tests/Support/SupportCollectionTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,17 @@ public function testFirstWithDefaultAndWithoutCallback($collection)
6969
$this->assertSame('default', $result);
7070
}
7171

72+
public function testFirstKey()
73+
{
74+
$data = new Collection(['foo' => 'bar', 'baz' => 'quz', 'qux' => 'quux']);
75+
76+
$this->assertSame('foo', $data->firstKey());
77+
78+
$data = new Collection(['foo', 'bar', 'baz', 'quz']);
79+
80+
$this->assertSame(0, $data->firstKey());
81+
}
82+
7283
/**
7384
* @dataProvider collectionClassProvider
7485
*/
@@ -330,6 +341,17 @@ public function testLastWithDefaultAndWithoutCallback($collection)
330341
$this->assertSame('default', $result);
331342
}
332343

344+
public function testLastKey()
345+
{
346+
$data = new Collection(['foo' => 'bar', 'baz' => 'quz', 'qux' => 'quux']);
347+
348+
$this->assertSame('qux', $data->lastKey());
349+
350+
$data = new Collection(['foo', 'bar', 'baz', 'quz']);
351+
352+
$this->assertSame(3, $data->lastKey());
353+
}
354+
333355
public function testPopReturnsAndRemovesLastItemInCollection()
334356
{
335357
$c = new Collection(['foo', 'bar']);

0 commit comments

Comments
 (0)