Skip to content

Commit 289b17d

Browse files
committed
Add array_find method
1 parent e85ab80 commit 289b17d

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/Php84/Php84.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,15 @@ public static function mb_lcfirst(string $string, ?string $encoding = null): str
6363

6464
return $firstChar . mb_substr($string, 1, null, $encoding);
6565
}
66+
67+
public static function array_find(array $array, callable $callback)
68+
{
69+
foreach ($array as $key => $value) {
70+
if ($callback($value, $key)) {
71+
return $value;
72+
}
73+
}
74+
75+
return null;
76+
}
6677
}

src/Php84/bootstrap.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,8 @@ function mb_ucfirst($string, ?string $encoding = null): string { return p\Php84:
2323
if (!function_exists('mb_lcfirst')) {
2424
function mb_lcfirst($string, ?string $encoding = null): string { return p\Php84::mb_lcfirst($string, $encoding); }
2525
}
26+
27+
if (!function_exists('array_find')) {
28+
function array_find(array $array, callable $callback) { return p\Php84::array_find($array, $callback); }
29+
}
30+

tests/Php84/Php84Test.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ public function testMbLcFirst(string $string, string $expected): void {
3030
$this->assertSame($expected, mb_lcfirst($string));
3131
}
3232

33+
/**
34+
* @dataProvider arrayFindDataProvider
35+
*/
36+
public function testArrayFind(array $array, callable $callback, $expected): void {
37+
$this->assertSame($expected, array_find($array, $callback));
38+
}
39+
3340
public static function ucFirstDataProvider(): array {
3441
return [
3542
['', ''],
@@ -68,4 +75,22 @@ public static function lcFirstDataProvider(): array {
6875
["ß", "ß"],
6976
];
7077
}
78+
79+
public static function arrayFindDataProvider(): array {
80+
$callable = function ($value): bool {
81+
return strlen($value) > 2;
82+
};
83+
84+
$callableKey = function ($value, $key): bool {
85+
return is_numeric($key);
86+
};
87+
88+
return [
89+
[[], $callable, null],
90+
[['a', 'aa', 'aaa', 'aaaa'], $callable, 'aaa'],
91+
[['a', 'aa'], $callable, null],
92+
[['a' => '1', 'b' => '12', 'c' => '123', 'd' => '1234'], $callable, '123'],
93+
[['a' => '1', 'b' => '12', 'c' => '123', 3 => '1234'], $callableKey, '1234'],
94+
];
95+
}
7196
}

0 commit comments

Comments
 (0)