Skip to content

Commit a7577cb

Browse files
committed
added Arrays::filter()
1 parent 21cef0e commit a7577cb

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/Utils/Arrays.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,27 @@ public static function every(iterable $array, callable $predicate): bool
369369
}
370370

371371

372+
/**
373+
* Returns a new array containing all key-value pairs matching the given $predicate.
374+
* The callback has the signature `function ($value, $key, $array): bool`.
375+
* @template K of array-key
376+
* @template V
377+
* @param array<K, V> $array
378+
* @param callable(V, K, array<K, V>): bool $predicate
379+
* @return array<K, V>
380+
*/
381+
public static function filter(array $array, callable $predicate): array
382+
{
383+
$res = [];
384+
foreach ($array as $k => $v) {
385+
if ($predicate($v, $k, $array)) {
386+
$res[$k] = $v;
387+
}
388+
}
389+
return $res;
390+
}
391+
392+
372393
/**
373394
* Returns an array containing the original keys and results of applying the given transform function to each element.
374395
* The function has signature `function ($value, $key, $array): mixed`.

tests/Utils/Arrays.filter().phpt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Arrays::filter()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Arrays;
10+
use Tester\Assert;
11+
12+
require __DIR__ . '/../bootstrap.php';
13+
14+
15+
Assert::same(
16+
['a' => 1, 'b' => 2],
17+
Arrays::filter(
18+
['a' => 1, 'b' => 2, 'c' => 3],
19+
fn($v) => $v < 3,
20+
),
21+
);
22+
23+
Assert::same(
24+
['c' => 3],
25+
Arrays::filter(
26+
['a' => 1, 'b' => 2, 'c' => 3],
27+
fn($v, $k) => $k === 'c',
28+
),
29+
);
30+
31+
Assert::same(
32+
['a' => 1, 'b' => 2, 'c' => 3],
33+
Arrays::filter(
34+
['a' => 1, 'b' => 2, 'c' => 3],
35+
fn($v, $k, $a) => $a === ['a' => 1, 'b' => 2, 'c' => 3]
36+
),
37+
);
38+
39+
Assert::same(
40+
[],
41+
Arrays::filter([], fn() => true)
42+
);

0 commit comments

Comments
 (0)