@@ -129,9 +129,7 @@ public static function contains(array $array, mixed $value): bool
129129 */
130130 public static function first (array $ array , ?callable $ predicate = null ): mixed
131131 {
132- $ key = $ predicate
133- ? self ::firstKey ($ array , $ predicate )
134- : array_key_first ($ array );
132+ $ key = self ::firstKey ($ array , $ predicate );
135133 return $ key === null ? null : $ array [$ key ];
136134 }
137135
@@ -145,19 +143,20 @@ public static function first(array $array, ?callable $predicate = null): mixed
145143 */
146144 public static function last (array $ array , ?callable $ predicate = null ): mixed
147145 {
148- $ key = $ predicate
149- ? self ::firstKey (array_reverse ($ array , preserve_keys: true ), $ predicate )
150- : array_key_last ($ array );
146+ $ key = self ::lastKey ($ array , $ predicate );
151147 return $ key === null ? null : $ array [$ key ];
152148 }
153149
154150
155151 /**
156- * Returns the key of first matching item the specified predicate or null if there is no such item.
152+ * Returns the key of first item (matching the specified predicate if given) or null if there is no such item.
157153 * The callback has the signature `function ($value, $key, $array): bool`.
158154 */
159- public static function firstKey (array $ array , callable $ predicate ): int |string |null
155+ public static function firstKey (array $ array , ? callable $ predicate = null ): int |string |null
160156 {
157+ if (!$ predicate ) {
158+ return array_key_first ($ array );
159+ }
161160 foreach ($ array as $ k => $ v ) {
162161 if ($ predicate ($ v , $ k , $ array )) {
163162 return $ k ;
@@ -168,12 +167,14 @@ public static function firstKey(array $array, callable $predicate): int|string|n
168167
169168
170169 /**
171- * Returns the key of last matching item the specified predicate or null if there is no such item.
170+ * Returns the key of last item (matching the specified predicate if given) or null if there is no such item.
172171 * The callback has the signature `function ($value, $key, $array): bool`.
173172 */
174- public static function lastKey (array $ array , callable $ predicate ): int |string |null
173+ public static function lastKey (array $ array , ? callable $ predicate = null ): int |string |null
175174 {
176- return self ::firstKey (array_reverse ($ array , preserve_keys: true ), $ predicate );
175+ return $ predicate
176+ ? self ::firstKey (array_reverse ($ array , preserve_keys: true ), $ predicate )
177+ : array_key_last ($ array );
177178 }
178179
179180
0 commit comments