diff --git a/src/Utils/Arrays.php b/src/Utils/Arrays.php index ed70578..73d8ed0 100644 --- a/src/Utils/Arrays.php +++ b/src/Utils/Arrays.php @@ -148,7 +148,7 @@ function (array $item) use ($key) { /** * @param iterable $collection - * @return mixed|null + * @return mixed */ public static function firstItem(iterable $collection) { @@ -168,6 +168,25 @@ public static function firstKey(iterable $collection) return $key; } + /** + * @param iterable $collection + * @return mixed + */ + public static function lastItem(iterable $collection) + { + return $collection[self::lastKey($collection)] ?? null; + } + + /** + * @param iterable $collection + * @return mixed + */ + public static function lastKey(iterable $collection) + { + end($collection); + return key($collection); + } + /** * @param array $array * @param string $prefix @@ -598,4 +617,5 @@ private static function trimValue($value) { return is_string($value) ? trim($value) : $value; } + } diff --git a/tests/UtilsTests/ArraysTest.php b/tests/UtilsTests/ArraysTest.php index c562927..4f89a1f 100644 --- a/tests/UtilsTests/ArraysTest.php +++ b/tests/UtilsTests/ArraysTest.php @@ -96,6 +96,16 @@ public function testFirstKey(): void $this->assertEquals('some-key', Arrays::firstKey(['some-key' => 'some-value', 2 => 'two'])); } + public function testLastItem(): void + { + $this->assertEquals(1, Arrays::lastItem([2, 1])); + } + + public function testLastKey(): void + { + $this->assertEquals(2, Arrays::lastKey([1 => 1, 2 => 2])); + } + public function testFlattenKeys(): void { $this->assertEquals( @@ -500,4 +510,5 @@ function ($a) { ) ); } + }