Skip to content

Core\Arr::filter

Core\Arr::filter(
    array<T> $a,
    callable(T, string): bool $predicate,
): array<T>

Keeps the entries of an array that a function accepts, and leaves the others out.

You give Core\Arr::filter an array and a function. The function receives the value and the key, and returns true for an entry you want to keep. A function that needs only the value declares only that one parameter.

The keys stay as they are. An entry kept from position 3 still has the key 3, so a filtered list can have gaps in its numbering. Use Core\Arr::values when you want the result numbered from 0 again.

Good to know: the function runs once for every entry, in the order the array holds them.

Parameters

  • $aarray<T>The array to filter.
  • $predicatecallable(T, string): boolCalled as ($value, $key) per entry. A truthy result keeps the entry. Truthy means the same here as in an if test.

Return value

Returns array<T>. The kept entries under their own keys, never renumbered; an empty array when nothing passes. For an array<E, T>, the result is an array<E, T> too.

Examples

Keep the numbers above a limit

<?nvs
// Keeps the entries a function accepts. `Core\Arr::filter` keeps the key of every
// entry it keeps, so the result can have gaps in its numbering.
array<int> $measurements = [4, 11, 7, 20];
array<int> $high = Core\Arr::filter($measurements, fn(int $n) => $n > 9);
// This prints `1: 11` and `3: 20`, the two keys these values had before.
foreach ($high as string $key => int $value) {
echo $key, ': ', $value, "\n";
}
Output
1: 11
3: 20

Keep the entries whose key matches

<?nvs
// Keeps entries by their key. The function may declare a second parameter, and
// `Core\Arr::filter` then gives it the key as well as the value.
array<string> $headers = [
'host' => 'shop.example',
'x-trace' => 'a91',
'accept' => 'text/html',
];
array<string> $forwarded = Core\Arr::filter(
$headers,
fn(string $value, string $key) => Core\Str::startsWith($key, 'x-'),
);
// This prints `x-trace: a91`, the one header whose name starts with `x-`.
foreach ($forwarded as string $name => string $value) {
echo $name, ': ', $value, "\n";
}
Output
x-trace: a91

Drop the fields a form left empty

<?nvs
// Removes the empty fields a form sent, so that only what a person filled in is
// saved. This is what programs use `Core\Arr::filter` for most often.
array<string> $form = [
'name' => 'Ida Weber',
'phone' => '',
'city' => 'Bonn',
'note' => '',
];
array<string> $filled = Core\Arr::filter($form, fn(string $value) => $value != '');
// This prints `saving 2 fields: name, city`.
echo 'saving ', Core\Arr::count($filled), ' fields: ',
Core\Str::join(Core\Arr::keys($filled), ', '), "\n";
Output
saving 2 fields: name, city