PHP array_filter() Function

Usage — The PHP array_filter() function is used to filter the elements of an array using a callback function.

It has the following syntax:

PHP

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Here is an example of using array_filter():

PHP

function is_odd($var) {
    return($var & 1);
}
$mixed = array(38754,8319,2,3,4);

print_r(array_filter($mixed, "is_odd"));
/* Output —
Array
(
    [1] => 8319
    [3] => 3
) */

Return Value — This function returns the filtered array.

Additional Information — It iterates over each value of the input array and passes it to the callback function. If the callback function returns TRUE, the current value from input is returned into the result array. Array keys are preserved.

PHP Version and Changelog — The array_filter() function is available in PHP 4 >= 4.0.6, PHP 5, PHP 7. The optional flag parameter was added in PHP 5.6.0 and can be set to ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH.

Relevant Functions — Other related PHP functions that you should know about are: array_map() which applies the callback to the elements of the given arrays, array_reduce() which iteratively reduces the array to a single value using a callback function and array_walk() which applies a user supplied function to every member of an array.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

array

The array parameter is used to specify the array to iterate over. This is a required parameter.

callback

The callback parameter is used to specify the callback function to use/ This is an optional parameter. Keep in mind that if no callback is supplied, all entries of array equal to FALSE will be removed.

flag

The flag parameter is used to specify a flag that determines what arguments are sent to callback. This is an optional parameter. It can have two possible values:

  • ARRAY_FILTER_USE_KEY will pass keys as the only argument to callback instead of the value.
  • ARRAY_FILTER_USE_BOTH will pass both value and key as arguments to callback instead of just using the key.

Working Examples

Here are some examples of using the array_filter() function without any callback:

PHP

$test = array( 0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => '');

print_r(array_filter($test));
/* Output —
Array
(
    [0] => foo
    [2] => -1
) */

Here is an example which shows how to use the optional flag parameter. You should note that with the ARRAY_FILTER_USE_BOTH flag, the value is passed to the callback function first and the key is passed later.

PHP

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

print_r(array_filter($arr, function($k) {
    return $k == 'b';
}, ARRAY_FILTER_USE_KEY));
/* Output —
Array
(
    [b] => 2
) */

print_r(array_filter($arr, function($v, $k) {
    return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
/* Output —
Array
(
    [b] => 2
    [d] => 4
) */

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. If you want a quick way to remove NULL, FALSE and Empty Strings (“”) but still leave values of 0 (zero), you can use the standard PHP function strlen as the callback function:

    PHP

    $result = array_filter( $array, 'strlen' );
    

    Suggested by - Anonymous

  2. Because array_filter() preserves keys, you should consider the resulting array to be an associative array even if the original array had integer keys for there may be holes in your sequence of keys. This means that, for example, json_encode will convert your result array into an object instead of an array. Call array_values() on the result array to guarantee json_encode gives you an array.

    Suggested by - Peter Robinett

  3. In case you are interested (like me) in filtering out elements with certain key-names, array_filter() won’t help you. Instead you can use the following:

    PHP

    $arr = array( 'element1' => 1, 'element2' => 2, 'element3' => 3, 'element4' => 4 );
    $filterOutKeys = array( 'element1', 'element4' );
    $filteredArr = array_diff_key( $arr, array_flip( $filterOutKeys ) )
    

    Result will be something like this:

    PHP

    ['element2'] => 2
    ['element3'] => 3

    Suggested by - niehztog

Further Reading

  1. You can read more about the PHP array_filter() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top