PHP 7.4.0RC4 Released!

array_filter

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

array_filterFiltra elementos de un array usando una función de devolución de llamada

Descripción

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

Recorre cada valor de array, pasándolos a la función callback. Si la función callback devuelve true, el valor actual desde array es devuelto al array resultante. Las claves del array se conservan.

Parámetros

array

El array a recorrer.

callback

La función de devolución de llamada a usar.

Si no se proporciona callback, todas las entradas de array iguales a FALSE (véase convetir a boolean) serán eliminadas.

flag

Indicador que determina qué argumentos se envían a callback:

  • ARRAY_FILTER_USE_KEY - pasar la clave como el único argumento a callback en lugar del valor
  • ARRAY_FILTER_USE_BOTH - pasar el valor y la clave como argumentos a callback en lugar del valor

Valores devueltos

Devuelve el array filtrado.

Historial de cambios

Versión Descripción
5.6.0 Se añadió el parámetro opcional flag y las constantes ARRAY_FILTER_USE_KEY y ARRAY_FILTER_USE_BOTH

Ejemplos

Ejemplo #1 Ejemplo de array_filter()

<?php
function impar($var)
{
    
// Retorna siempre que el número entero sea impar
    
return($var 1);
}

function 
par($var)
{
    
// Retorna siempre que el número entero sea par
    
return(!($var 1));
}

$array1 = array("a"=>1"b"=>2"c"=>3"d"=>4"e"=>5);
$array2 = array(6789101112);

echo 
"Impar :\n";
print_r(array_filter($array1"impar"));
echo 
"Par:\n";
print_r(array_filter($array2"par"));
?>

El resultado del ejemplo sería:

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

Ejemplo #2 array_filter() sin callback

<?php

$entrada 
= array(
             
=> 'foo',
             
=> false,
             
=> -1,
             
=> null,
             
=> ''
          
);

print_r(array_filter($entrada));
?>

El resultado del ejemplo sería:

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

Ejemplo #3 array_filter() con flag

<?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));
?>

El resultado del ejemplo sería:

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

Notas

Precaución

Si el array se cambia desde la función de devolución de llamada (p.ej. un elemento añadido, suprimido o desestablecido) el comportamiento de esta función no estará definido.

Ver también

  • array_map() - Aplica la retrollamada a los elementos de los arrays dados
  • array_reduce() - Reduce iterativamente un array a un solo valor usando una función llamada de retorno
  • array_walk() - Aplicar una función proporcionada por el usuario a cada miembro de un array

add a note add a note

User Contributed Notes 37 notes

up
442
Anonymous
6 years ago
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' );

?>
up
176
Peter Robinett
9 years ago
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.
up
72
niehztog
10 years ago
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
up
31
rolf at example dot com
8 years ago
Here is how you could easily delete a specific value from an array with array_filter:

<?php
$array
= array (1, 3, 3, 5, 6);
$my_value = 3;
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } );
print_r($filtered_array);
?>

output:

Array
(
    [0] => 1
    [3] => 5
    [4] => 6
)
up
22
manwe at inversion dot pl
5 years ago
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');
up
16
robbieaverill at gmail dot com
4 years ago
If you want to use array_filter with a class method as the callback, you can use a psuedo type callback like this:

<?php
class Test
{
    public function
doFilter($array)
    {
        return
array_filter($array, array($this, 'callbackMethodName'));
    }

    protected function
callbackMethodName($element)
    {
        return
$element % 2 === 0;
    }
}

$example = new Test;
print_r($example->doFilter(range(1, 10)));
?>

Will return even numbers.
up
26
marc dot vanwoerkom at fernuni-hagen dot de
15 years ago
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.
up
24
webdesign at blackbyrd dot biz
10 years ago
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)
);
up
17
romain dot lamarche at gmail dot com
10 years ago
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);
  }
?>
up
3
g dot kuizinas at anuary dot com
6 years ago
<?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);
?>
up
12
lisachenko dot it at HUMAN dot gmail dot com
8 years ago
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().
up
7
yuzhen huang
4 years ago
from php  5.3,  we use anonymous function as second argument:

$a = array('a'=>1, 'b'=>2, 'c'=>false, 'd'=>0);
$b = array_filter($a, function($v){return $v !== 0;});
var_dump($b);

output:
array(3) {
  'a' =>
  int(1)
  'b' =>
  int(2)
  'c' =>
  bool(false)
}
up
8
tx at tshwarelo-leaka dot co dot za
6 years ago
To get rid of all white space in an array without looping.
<?php
   $array
= array(5, "   ", 2, NULL, 13, "", 7, "\n", 4, "\t");
  
print_r($array);
  
$result = array_filter($array, create_function('$a','return preg_match("#\S#", $a);'));                
  
print_r($result);
?>
Array
(
    [0] => 5
    [1] =>   
    [2] => 2
    [3] =>
    [4] => 13
    [5] =>
    [6] => 7
    [7] =>

    [8] => 4
    [9] =>    
)
Array
(
    [0] => 5
    [2] => 2
    [4] => 13
    [6] => 7
    [8] => 4
)
up
1
nicolaj dot knudsen at gmail dot com
2 years ago
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.
up
5
marc dot gray at gmail dot com
5 years ago
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.
up
1
Martin
12 years ago
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.
up
2
iancudanielc () gmail ! com
4 years ago
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');

?>
up
2
jtreminio at gmail dot com
7 years ago
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();
?>
up
2
avl
5 years ago
nice trick:

$array_out = array_filter($array_in, function($var) use($array_other) {
            return in_array($var, $array_other) ? true : false;
});
up
1
ajohnson at speakeasy dot org
17 years ago
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);
?>
up
0
raj at rafa dot eu dot org
1 year ago
Here is a simple array_grep() function that works similarly to 'grep' command, ie. filters array elements that match a given regular expression.

It's a bit ugly as it uses a global variable $__array_grep_regex to pass the regular expression to the callback function. I couldn't find a better way to do it. Anyway, here it is:

<?php
$__array_grep_regex
="";

function
array_grep($arr, $regex) {
global
$__array_grep_regex;
$__array_grep_regex=$regex;
return
array_filter($arr, function($val) {
  global
$__array_grep_regex;
  return
preg_match($__array_grep_regex, $val);
});
}
?>
up
-2
nsrwork(dog)gmail
1 year ago
If we need to find array in the multidimenssional array (with ignore keys!)

// where we will find
$arrays = [
    ['c','b','a'],  ['e','f','g'],  ['j','h','t']
];

// what we will find   
$array = ['a','b','c'];

function isArrayExist($arrays, $array)
{
    return (bool) array_filter($arrays, function ($_array) use ($array) {
        return !array_diff($array, $_array);
    });
}

//Output
true
up
-2
bimal at sanjaal dot com
1 year ago
I needed to filter specific files. glob was a good option but had issues being case sensitive. And at the same time, I had to filter the directory names like ".", "..", ".git", etc which could be complex.

I used a snippet as below, where I could implement this complex filter. Just modify your method: image_file.

<?php

class handlers
{
    private
$path;
    public function
__construct($path)
    {
       
$this->path = realpath($path);
    }

    public function
image_file($file="abc.png")
    {
       
$is_image_file = is_file($this->path."/".$file);

        return
$is_image_file;
    }
}

$path = realpath("../../gallery-200x400");

$files = scandir($path);
print_r($files);

$files = array_filter($files, array(new handlers($path), "image_file"), ARRAY_FILTER_USE_BOTH);
print_r($files);
?>
up
-2
jimmmy dot chief at gmail dot com
2 years ago
Hi, when using your annonymous function to filter the array, DO NOT cast returning value as bool.
Any value won't be filtered that way.

example:

$reader = array(
    1,2,3,2,1,2,1,2,1
);

$a = array_filter($reader, function ($var) {
    return (bool) $var == 2;    //returns whole array
    return $var == 2;           //filter values
});

echo count($a);     //9 with cast as bool, 4 otherwise
up
0
njt1982 at yahoo dot com
4 years ago
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.
up
0
qeremy [atta] gmail [dotta] com
6 years ago
Here is key-passed array_filter function.

<?php
function arrayfilter(array $array, callable $callback = null) {
    if (
$callback == null) {
       
$callback = function($key, $val) {
            return (bool)
$val;
        };
    }
   
$return = array();
    foreach (
$array as $key => $val) {
        if (
$callback($key, $val)) {
           
$return[$key] = $val;
        }
    }
    return
$return;
}

$test_array = array('foo', 'a' => 'the a', 'b' => 'the b', 11 => 1101, '', null, false, 0);

$array = arrayfilter($test_array, function($key, $val) {
   return
is_string($key);
});
print_r($array);
/*
Array
(
    [a] => the a
    [b] => the b
)
*/

$array = arrayfilter($test_array);
print_r($array);
/*
Array
(
    [0] => foo
    [a] => the a
    [b] => the b
    [11] => 1101
)
*/
?>
up
0
acid24 at gmail dot com
9 years ago
A function that allows filtering an array by keys:

<?php
function array_filter_key( $input, $callback ) {
    if ( !
is_array( $input ) ) {
       
trigger_error( 'array_filter_key() expects parameter 1 to be array, ' . gettype( $input ) . ' given', E_USER_WARNING );
        return
null;
    }
   
    if ( empty(
$input ) ) {
        return
$input;
    }
   
   
$filteredKeys = array_filter( array_keys( $input ), $callback );
    if ( empty(
$filteredKeys ) ) {
        return array();
    }
   
   
$input = array_intersect_key( array_flip( $filteredKeys ), $input );
   
    return
$input;
}

?>

Example:

<?php
$input
= array_flip( range( 'a', 'z' ) );

$consonants = array_filter_key( $arr, function( $elem ) {
   
$vowels = "aeiou";
    return
strpos( $vowels, strtolower( $elem ) ) === false;
} );
?>

Outputs:

array(21) {
  ["b"]=>
  int(1)
  ["c"]=>
  int(2)
  ["d"]=>
  int(3)
  ["f"]=>
  int(5)
  ["g"]=>
  int(6)
  ["h"]=>
  int(7)
  ["j"]=>
  int(9)
  ["k"]=>
  int(10)
  ["l"]=>
  int(11)
  ["m"]=>
  int(12)
  ["n"]=>
  int(13)
  ["p"]=>
  int(15)
  ["q"]=>
  int(16)
  ["r"]=>
  int(17)
  ["s"]=>
  int(18)
  ["t"]=>
  int(19)
  ["v"]=>
  int(21)
  ["w"]=>
  int(22)
  ["x"]=>
  int(23)
  ["y"]=>
  int(24)
  ["z"]=>
  int(25)
}
up
0
chrisstocktonaz at gmail dot com
10 years ago
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');
}
?>
up
0
darren at dazwin dot com
11 years ago
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;
}
?>
up
0
Maxwel Leite
15 years ago
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;
}
?>
up
0
ajohnson at speakeasy dot org
17 years ago
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);
?>
up
-2
skd2 at ece dot msstate dot edu
16 years ago
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.

<?php
function array_cleanse(&$arr){

$temp = array();
reset($arr);
if(
count($arr) == 0) return "";

foreach(
$arr as $key=>$val):

(
is_array($val))? array_cleanse($val) : NULL;
(
$val)? $temp[$key] = $val : NULL;

endforeach;

$arr = $temp;
reset($arr);
}
?>

$arr1 = array('a'=>20,'b'=>array(''),'c'=>array(1,0,2),'d'=>0);
array_cleanse($arr1);
$arr1 will be array('a'=>20,'c'=>array(1,2))

array_filter may not be used as it does not modify the array within itself.
up
-1
John Erck: erck0006 at junkyo dot gmail dot com
7 years ago
<?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 */
up
-1
tomasz at trejderowski dot pl
6 years ago
Read "callback" parameter note with understanding (as well as "converting to boolean" chapter). Keep in midn, that 0, both:

* integer: 0 and
* float: 0.00

evaluates to boolean FALSE! And therefore all array nodes, that have such value WILL ALSO BE FILTERED by array_filter(), with default call back. Unless you provide your own callback function, that will (for example) filter only empty strings and NULLs, but leave "zeros" untouched.

Some people (including me) might be surprised to find this out.
up
-1
spam dot 2011 at rebell dot at
7 years ago
If you have not noticed already - array_filter() can be used to remove empty elements, since an empty string considered "false", if you not specify a callback

Keep in mind, that this will remove also some other values - so if you want a quick "remove empty elements from array" this function will be fine, as long as you dont have anything to keep, which casts to "false"
up
-1
Anonymous
1 year ago
<?php
function odd($var)
{
   
// returns whether the input integer is odd
   
return($var & 1);
}

function
even($var)
{
   
// returns whether the input integer is even
   
return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo
"Odd :\n";
print_r(array_filter($array1, "odd"));
echo
"Even:\n";
print_r(array_filter($array2, "even"));
?>

shouldtnt the '&' operators in the function be a '%' ? Is this a typo or do I not undertsand PHP
up
-1
m dot abbasian at outlook dot com
5 years ago
If you want a quick way to Find Numbers ( remove NULL, FALSE and Empty Strings (""), all Strings) but leave values of 0 (zero)
eg:
<?php
/*
Find Numbers (removes all NULL, FALSE and Empty Strings, all Strings) but leaves 0 (zero) values
*/

$result = array_filter( array( "0",0,1,2,3,'text' ) , 'is_numeric' );

var_dump($result);
/*
  array (size=5)
  0 => string '0' (length=1)
  1 => int 0
  2 => int 1
  3 => int 2
  4 => int 3
*/
?>
To Top