Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to filter an array

Short answer

array_filter() keeps the elements for which the function returns true:

<?php
 
$numbers = [5, 12, 8, 20];
 
echo implode(', ', array_filter($numbers, fn ($n) => $n > 10));

Output:

12, 20

Removing empty values

Without a test function, empty strings, zeros and null are removed:

<?php
 
print_r(array_values(array_filter(['a', '', 'b', null])));

Output:

Array
(
    [0] => a
    [1] => b
)

By key

With the ARRAY_FILTER_USE_KEY flag the function receives the key instead of the value:

<?php
 
$data = ['name' => 'Anna', 'password' => 'secret', 'age' => 25];
 
print_r(array_filter($data, fn ($key) => $key !== 'password', ARRAY_FILTER_USE_KEY));

Output:

Array
(
    [name] => Anna
    [age] => 25
)

Functions used in this recipe

  • array_filter — Keeps the array elements that pass a test.
  • array_map — Applies a function to every element of an array.

Thanks for reading!

Donate to the site — we work hard for you.