array_filter

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

array_filter使用回调函数过滤数组的元素

说明

array_filter ( array $array , callable|null $callback = null , int $mode = 0 ) : array

遍历 array 数组中的每个值,并将每个值传递给 callback 回调函数。 如果 callback 回调函数返回 true,则将 array 数组中的当前值返回到结果 array 数组中。

返回结果 array 数组的键名(下标)会维持不变,如果 array 参数是索引数组,返回的结果 array 数组键名(下标)可能会不连续。 可以使用 array_values() 函数对数组重新索引。

参数

array

要遍历的数组

callback

使用的回调函数

如果没有提供 callback 回调函数,将删除数组中 array 的所有"空"元素。 有关 PHP 如何判定"空"元素,请参阅 empty()

mode

决定哪些参数发送到 callback 回调的标志:

  • ARRAY_FILTER_USE_KEY - 将键名作为 callback 回调的唯一参数,而不是值
  • ARRAY_FILTER_USE_BOTH - 将值和键都作为参数传递给 callback 回调,而不是仅传递值
默认值为 0 ,只传递值作为 callback 回调的唯一参数。

返回值

返回过滤后的数组。

更新日志

版本 说明
8.0.0 callback 回调现在可以为空(nullable)。
5.6.0 添加可选的 mode 标志和常量( ARRAY_FILTER_USE_KEYARRAY_FILTER_USE_BOTH

范例

Example #1 array_filter() 示例

<?php
function odd($var)
{
    
// 返回输入整数是否为奇数(单数)
    
return $var 1;
}
function 
even($var)
{
    
// 返回输入整数是否为偶数
    
return !($var 1);
}
$array1 = ['a' => 1'b' => 2'c' => 3'd' => 4'e' => 5];
$array2 = [6789101112];
echo 
"Odd :\n";
print_r(array_filter($array1"odd"));
echo 
"Even:\n";
print_r(array_filter($array2"even"));
?>

以上例程会输出:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Example #2 array_filter() 不使用 callback 参数时

<?php
$entry 
= [
    
=> 'foo',
    
=> false,
    
=> -1,
    
=> null,
    
=> '',
    
=> '0',
    
=> 0,
];
print_r(array_filter($entry));
?>

以上例程会输出:

Array
(
    [0] => foo
    [2] => -1
)

Example #3 array_filter() 不使用 mode 参数时

<?php
$arr 
= ['a' => 1'b' => 2'c' => 3'd' => 4];
var_dump(array_filter($arr, function($k) {
    return 
$k == 'b';
}, 
ARRAY_FILTER_USE_KEY));
var_dump(array_filter($arr, function($v$k) {
    return 
$k == 'b' || $v == 4;
}, 
ARRAY_FILTER_USE_BOTH));
?>

以上例程会输出:

array(1) {
  ["b"]=>
  int(2)
}
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}

注释

Caution

不应该在回调函数中改变数组(如:添加、删除或销毁"unset"当前数组和里面的元素),否则此函数的行为将不可预测。

参见

  • array_map() - 为数组的每个元素应用回调函数
  • array_reduce() - 用回调函数迭代地将数组简化为单一的值
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

stef at gigamedium dot com 09-Dec-2020 12:00
To filter out empty arrays, put the arrays you need filtering in an array and pass through array_filter.

$array1 = [5, 6];
$array2 = [];
$array3 = [7,9];

$array = array_filter(array($array1, $array2, $array3));

print_r($array)

Results in:
Array (
  [5,6] , [7,9]
}
Al Amin Chayan (mail at chayan dot me) 22-Sep-2020 05:43
/**
   * Remove key from multidimensional array
   *
   * @param array $request
   * @param array $keys
   *
   * @return array
   */
function request_filter(array $request, array $keys) {
    array_walk($request, function (&$value, $key) use ($keys) {
        if(is_array($value)) {
            $value = request_filter($value, $keys);
        }
    });

    return array_filter ($request, function ($value, $key) use ($keys) {
        return ! in_array($key, $keys);
    }, ARRAY_FILTER_USE_BOTH);
}

$data = [
  'a' => 'A',
  'password' => 123,
  'data' => [
      'b' => 'B',
      'data2' => [
           'c' => 'C',
            'password' => 545,
    ],
    'password' => 321,
  ]
];

print_r(request_filter($data, ['password']));

Output will be:
Array
(
    [a] => A
    [data] => Array
        (
            [b] => B
            [data2] => Array
                (
                    [c] => C
                )

        )

)
nicolaj dot knudsen at gmail dot com 05-Apr-2017 12:05
If you like me have some trouble understanding example #1 due to the bitwise operator (&) used, here is an explanation.

The part in question is this callback function:

<?php
function odd($var)
{
   
// returns whether the input integer is odd
   
return($var & 1);
}
?>

If given an integer this function returns the integer 1 if $var is odd and the integer 0 if $var is even.
The single ampersand, &, is the bitwise AND operator. The way it works is that it takes the binary representation of the two arguments and compare them bit for bit using AND. If $var = 45, then since 45 in binary is 101101 the operation looks like this:

45 in binary: 101101
1 in binary:  000001
              ------
result:       000001

Only if the last bit in the binary representation of $var is changed to zero (meaning that the value is even) will the result change to 000000, which is the representation of zero.
njt1982 at yahoo dot com 30-Apr-2015 01:18
If you have an array of KV pairs and you want all the items where a value is X, you dont need to make a callback for array_filter. You can use array_intersect:

<?php
print_r
(array_intersect(
  array(
   
'a' => 1,
   
'b' => 1,
   
'c' => 1,
   
'd' => 2,
   
'e' => 2,
   
'f' => 2,
  ),
  array(
1)
));

Array
(
    [
a] => 1
   
[b] => 1
   
[c] => 1
)
?>

The advantage of this approach is you can pass variables into the second array without needing to worry about variable scope and function parameters for array_filter.
iancudanielc () gmail ! com 09-Jan-2015 08:56
If you want to pass the key to the callback function before PHP 5.6.0 (when the flag parameter wasn't implemented):

<?php

$result
= array_filter(array_keys($array), 'is_int');

?>
manwe at inversion dot pl 21-Sep-2014 12:33
array_filter remove also FALSE and 0. To remove only NULL's use:

$af = [1, 0, 2, null, 3, 6, 7];

function is_not_null($val){
    return !is_null($val);
}
$af = array_filter($af, 'is_not_null');
marc dot gray at gmail dot com 29-Apr-2014 10:44
My favourite use of this function is converting a string to an array, trimming each line and removing empty lines:

<?php
$array
= array_filter(array_map('trim', explode("\n", $string)), 'strlen');
?>

Although it states clearly that array keys are preserved, it's important to note this includes numerically indexed arrays. You can't use a for loop on $array above without processing it through array_values() first.
avl 04-Nov-2013 12:25
nice trick:

$array_out = array_filter($array_in, function($var) use($array_other) {
            return in_array($var, $array_other) ? true : false;
});
g dot kuizinas at anuary dot com 26-Mar-2013 11:10
<?php
function array_filter_recursive ($data) {
   
$original = $data;

   
$data = array_filter($data);
   
   
$data = array_map(function ($e) {
        return
is_array($e) ? array_filter_recursive($e) : $e;
    },
$data);

    return
$original === $data ? $data : array_filter_recursive($data);
}

$data = ['a' => 0, 'b' => [], 'c' => [[]], 'd' => [[[[]]]], 'e' => 'foo', 'f' => [[['a']]], [true], [[],['a'], [true, false]]];

$data = array_filter_recursive($data);
?>
Anonymous 13-Jan-2013 05:52
If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:
eg:
<?php

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

?>
jtreminio at gmail dot com 04-Oct-2012 07:11
You can use array_filter from within a class to access a protected method from that same class:

<?php

class Bar {
    public function
foo()
    {
       
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

       
print_r(array_filter($array1, array($this, 'naz')));
    }

    protected function
baz($var)
    {
        return(
$var & 1);
    }
}

$bar = new Bar();
$bar->foo();
?>
John Erck: erck0006 at junkyo dot gmail dot com 04-Apr-2012 08:09
<?php
// ARRAY FILTER RECURSIVE USING CLASS, STATIC METHOD, AND ANONYMOUS CALLBACK FUNCTION
// NOTE THAT THE CALLBACK HAS ACCESS TO BOTH THE KEY AND VALUE

// THE CLASS (FOR YOU TO COPY)
class ArrayUtil
{
    public static function
FilterRecursive(Array $source, $fn)
    {
       
$result = array();
        foreach (
$source as $key => $value)
        {
            if (
is_array($value))
            {
               
$result[$key] = self::FilterRecursive($value, $fn);
                continue;
            }
            if (
$fn($key, $value))
            {
               
$result[$key] = $value; // KEEP
               
continue;
            }
        }
        return
$result;
    }
}

// EXAMPLE ANONYMOUS CALLBACK FUNCTION
$fn = function ($key, $value)
{
    if (
strpos($key, 'drop') !== FALSE)
    {
        return
FALSE; // DROP
   
}
    return
TRUE; // KEEP
};

// EXAMPLE PRE FILTER TEST DATA
$preFilter = array(
   
'a' => 'one',
   
'b' => array(
       
'example_drop' => 'filter me out',
       
'example_keep' => 'keep me',
    ),
   
'c' => 'three',
);

// EXAMPLE USAGE CODE
echo '// print_r($preFilter);' . "\n";
print_r($preFilter);
$postFilter = ArrayUtil::FilterRecursive($preFilter, $fn);
echo
"\n";
echo
'// print_r($postFilter);' . "\n";
print_r($postFilter);

/* OUTPUT OPEN
// print_r($preFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_drop] => filter me out
            [example_keep] => keep me
        )

    [c] => three
)

// print_r($postFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_keep] => keep me
        )

    [c] => three
)
OUTPUT CLOSE */
lisachenko dot it at HUMAN dot gmail dot com 22-Jul-2011 12:54
You can access the current key of array by passing a reference to array into callback function and call key() and next() method in the callback function:
<?php
$data
= array('first' => 1, 'second' => 2, 'third' => 3);
$data = array_filter($data, function ($item) use (&$data) {
    echo
"Filtering key ", key($data), '<br>', PHP_EOL;
   
next($data);
    return
false;
});
?>

However be careful with array internal pointer or use reset() method before calling array_filter().
Peter Robinett 12-Aug-2010 08:09
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.
webdesign at blackbyrd dot biz 08-Oct-2009 01:00
Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given

<?php
   
/*
     * filtering an array
     */
   
function filter_by_value ($array, $index, $value){
        if(
is_array($array) && count($array)>0
        {
            foreach(
array_keys($array) as $key){
               
$temp[$key] = $array[$key][$index];
                
                if (
$temp[$key] == $value){
                   
$newarray[$key] = $array[$key];
                }
            }
          }
      return
$newarray;
    }
?>

Example:

<?php
$results
= array(
  
0 => array('key1' => '1', 'key2' => 2, 'key3' => 3),
  
1 => array('key1' => '12', 'key2' => 22, 'key3' => 32)
);

$nResults = filter_by_value($results, 'key2', '2');
?>

Output :

array(
    0 => array('key1' => '1', 'key2' => 2, 'key3' => 3)
);
chrisstocktonaz at gmail dot com 30-Apr-2009 09:34
I use the following to see if a array consist of scalar values or null, but of course you could mix it up using any of the is_ functions.

<?php
if(count($data) !== count(array_filter($data, 'is_scalar') + array_filter($data, 'is_null'))) {
  throw new
Exception('Array did not consist of scalar and null values');
}
?>
niehztog 30-Dec-2008 01:27
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:
['element2'] => 2
['element3'] => 3
romain dot lamarche at gmail dot com 11-Dec-2008 06:39
This function filters an array and remove all null values recursively.

<?php
 
function array_filter_recursive($input)
  {
    foreach (
$input as &$value)
    {
      if (
is_array($value))
      {
       
$value = array_filter_recursive($value);
      }
    }
   
    return
array_filter($input);
  }
?>

Or with callback parameter (not tested) :

<?php
 
function array_filter_recursive($input, $callback = null)
  {
    foreach (
$input as &$value)
    {
      if (
is_array($value))
      {
       
$value = array_filter_recursive($value, $callback);
      }
    }
   
    return
array_filter($input, $callback);
  }
?>
darren at dazwin dot com 08-Oct-2008 11:44
Regarding comment about trimming empty strings, the code posted will get into an infinite loop if the array is reduced to zero elements. The following might be better:

<?php
function array_trim($array) {
    while (!empty(
$array) and strlen(reset($array)) === 0) {
       
array_shift($array);
    }
    while (!empty(
$array) and strlen(end($array)) === 0) {
       
array_pop($array);
    }
    return
$array;
}
?>
Martin 04-Sep-2007 10:56
This function trims empty strings from the beginning and end of an array.
It's useful when outputing plaintext files on a page and you want to skip empty lines at the beginning and end, but not within the text.

<?php
function array_trim($array) {
    while (
strlen(reset($array)) === 0) {
       
array_shift($array);
    }
    while (
strlen(end($array)) === 0) {
       
array_pop($array);
    }
    return
$array;
}
?>

You might want to trim each element too.
marc dot vanwoerkom at fernuni-hagen dot de 05-Jul-2004 08:09
Some of PHP's array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:

<?php
  array_filter
() -> filter(),
 
array_map() -> map(),
 
array_reduce() -> foldl() ("fold left")
?>

Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.

The array functions mentioned above allow you compose new functions on arrays.

E.g. array_sum = array_map("sum", $arr).

This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.

E.g. a mathematician might state

  map(f o g) = map(f) o map(g)

the so called "loop fusion" law.

Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).

I can't get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
Maxwel Leite 11-May-2004 08:17
For any type of array. Basead in redshift code.

<?php
function array_clean ($array, $todelete = false, $caseSensitive = false) {
    foreach(
$array as $key => $value) {
        if(
is_array($value)) {
           
$array[$key] = array_clean($array[$key], $todelete, $caseSensitive);
        }
        else {
            if(
$todelete) {
                if(
$caseSensitive) {
                    if(
strstr($value ,$todelete) !== false)
                        unset(
$array[$key]);
                }
                else {
                    if(
stristr($value, $todelete) !== false)
                        unset(
$array[$key]);
                }
            }
            elseif (empty(
$value)) {
                unset(
$array[$key]);
            }
        }
    }
    return
$array;
}
?>
ajohnson at speakeasy dot org 27-Sep-2002 12:42
be careful with the above function "array_delete"'s use of the stristr function, it could be slightly misleading. consider the following:

<?php
function array_delete($array, $filterforsubstring){
   
$thisarray = array ();
    foreach(
$array as $value)
        if(
stristr($value, $filterforsubstring)===false && strlen($value)>0)
           
$thisarray[] = $value;
    return
$thisarray;
}

function
array_delete2($array, $filterforstring, $removeblanksflag=0){
   
$thisarray = array ();
    foreach(
$array as $value)
        if(!(
stristr($value, $filterforstring) && strlen($value)==strlen($filterforstring))
                && !(
strlen($value)==0 && $removeblanksflag))
           
$thisarray[] = $value;
    return
$thisarray;
}

function
array_delete3($array, $filterfor, $substringflag=0, $removeblanksflag=0){
   
$thisarray = array ();
    foreach(
$array as $value)
        if(
            !(
stristr($value, $filterfor)
                && (
$substringflag || strlen($value)==strlen($filterfor))
            )
            && !(
strlen($value)==0 && $removeblanksflag)
        )
           
$thisarray[] = $value;
    return
$thisarray;
}

$array1 = array ('the OtHeR thang','this', 'that', 'OtHer','', 9, 101, 'fifty', ' oTher', 'otHer ','','other','Other','','other blank things');

echo
"<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo
"array_delete(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other");

echo
"array_delete2(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other",1);

echo
"array_delete2(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",1);

echo
"array_delete3(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",0,1);

echo
"array_delete3(\$array1, \"Other\",0,1):\n";
print_r($array2);
 
?>
ajohnson at speakeasy dot org 17-Aug-2002 01:04
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn't* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):

<?php
function array_delete($array, $filterfor){
 
$thisarray = array ();
  foreach(
$array as $value)
    if(
stristr($value, $filterfor)===false && strlen($value)>0)
     
$thisarray[] = $value;
  return
$thisarray;
}

$array1 = array ('OtHeR','this', 'that', 'Other','', 9, 101, 'fifty', 'other','','');

echo
"<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo
"filtered:\n";
print_r($array2);
?>