Skip to content

Commit 1102da9

Browse files
committed
Add Arr::filterValue method to filter array value in recursive way
1 parent ebb22b2 commit 1102da9

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/Helper/Arr.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,24 @@ public static function isSubset(
658658
return true;
659659
}
660660

661+
/**
662+
* Filter array values
663+
* @param array<mixed> $array
664+
* @return array<mixed>
665+
*/
666+
public static function filterValue(array $array): array
667+
{
668+
foreach ($array as $key => &$value) {
669+
if (is_array($value)) {
670+
// Recursively filter the sub-array
671+
$value = self::filterValue($value);
672+
}
673+
}
674+
675+
// Filter the current level, removing empty values and arrays
676+
return array_filter($array);
677+
}
678+
661679
/**
662680
* Filters array according to rules specified.
663681
* @param array<mixed> $array

tests/Helper/ArrTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,21 @@ public function testNormalizeArgumentsDefault(): void
219219
public function commonDataProvider(): array
220220
{
221221
return [
222+
[
223+
'filterValue',
224+
[[2, 4, 5]],
225+
[2, 4, 5]
226+
],
227+
[
228+
'filterValue',
229+
[[2, 4, 5, null, 'a' => 2, '']],
230+
[2, 4, 5, 'a' => 2]
231+
],
232+
[
233+
'filterValue',
234+
[['a' => [2, null], [1, 2]]],
235+
['a' => [2], [1, 2]]
236+
],
222237
[
223238
'first',
224239
[[2, 4, 5]],

0 commit comments

Comments
 (0)