PHP Doku:: Filtert Elemente eines Arrays mittels einer Callback-Funktion - function.array-filter.html
Aktuelle Suchanfrage: array_filter - 51 Treffer
  1 array_filter
Filtert Elemente eines Arrays mittels einer Callback-Funktion - function.array-filter.html
  2 array_fill
Füllt ein Array mit Werten - function.array-fill.html
  3 array_flip
Vertauscht alle Schlüssel mit ihren zugehörigen Werten in einem Array - function.array-flip.html
  4 array_reduce
Iterative Reduktion eines Arrays zu einem Wert mittels einer Callbackfunktion - function.array-reduce.html
  5 array_map
Wendet eine Callback-Funktion auf die Elemente von Arrays an - function.array-map.html
  6 Funktionsindex
Funktionsindex - indexes.html
  7 Laufzeit-Konfiguration
Laufzeit-Konfiguration - apc.configuration.html
  8 Arrays
Arrays - book.array.html
  9 Datenfilterung
Datenfilterung - book.filter.html
 10 Function Handling
Function Handling - book.funchand.html
mehr Ergebnisse anzeigen...

Bisherige Suchanfragen: (1) anzeigen

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenArraysArray Funktionenarray_filter

Ein Service von Reinhard Neidl - Webprogrammierung.

Array Funktionen

<<array_fill

array_flip>>

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filterFiltert Elemente eines Arrays mittels einer Callback-Funktion

Beschreibung

array array_filter ( array $input [, callback $callback ] )

Iteriert über jeden Wert im Array input und übergibt diesen der Callbackfunktion callback. Gibt die Funktion callback true zurück, so wird der aktuelle Wert von input in das Ergebnis-Array geschrieben. Die Schlüssel des Arrays bleiben erhalten.

Parameter-Liste

input

Das Array, über das iteriert werden soll

callback

Die zu verwendende Callbackfunktion

Falls die Funktion callback nicht angegeben wurde, werden alle Einträge des Arrays entfernt, die FALSE sind. Schauen Sie sich Konvertierung in Booleans für mehr Informationen hierzu an.

Rückgabewerte

Gibt das gefilterte Array zurück.

Beispiele

Beispiel #1 array_filter()-Beispiel

<?php
function ungerade($var)
{
    return(
$var 1);
}

function 
gerade($var)
{
    return(!(
$var 1));
}

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

echo 
"Ungerade :\n";
print_r(array_filter($array1"ungerade"));
echo 
"Gerade:\n";
print_r(array_filter($array2"gerade"));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #2 array_filter() ohne callback

<?php

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

print_r(array_filter($entry));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Anmerkungen

Achtung

Wird das Array durch die Callbackfunktion verändert (z.B. hinzufügen oder löschen von Elementen oder ein unset-Aufruf), so ist das Verhalten dieser Funktion undefiniert.

Siehe auch

  • array_map() - Wendet eine Callback-Funktion auf die Elemente von Arrays an
  • array_reduce() - Iterative Reduktion eines Arrays zu einem Wert mittels einer Callbackfunktion
  • array_walk() - Wendet eine Benutzerfunktion auf jedem Element eines Arrays an


40 BenutzerBeiträge:
- Beiträge aktualisieren...
breich at reich-consulting dot net
15.12.2010 20:19
I built the following array_remove_keys() function to
remove one or more keys from an array.

<?php
 
function array_remove_keys($array, $keys = array()) {
 
   
// If array is empty or not an array at all, don't bother
    // doing anything else.
   
if(empty($array) || (! is_array($array))) {
        return
$array;
    }
 
   
// If $keys is a comma-separated list, convert to an array.
   
if(is_string($keys)) {
       
$keys = explode(',', $keys);
    }
 
   
// At this point if $keys is not an array, we can't do anything with it.
   
if(! is_array($keys)) {
        return
$array;
    }
 
   
// array_diff_key() expected an associative array.
   
$assocKeys = array();
    foreach(
$keys as $key) {
       
$assocKeys[$key] = true;
    }
 
    return
array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
   
'name' => 'Brian',
   
'address1' => '98 Market St.',
   
'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, 'address2');
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/
?>
rolf at example dot com
8.11.2010 20:06
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
)
Peter Robinett
12.08.2010 17: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.
acid24 at gmail dot com
26.07.2010 14:58
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)
}
Ant P.
13.03.2010 17:58
If you're using filter_input_array, the values will be null on failure and anything else on success. Because array_filter by default removes false, 0 and "" you need to do extra work like this:
<?php
$input_array
= filter_input_array(INPUT_GET, array(
 
'var1' => FILTER_VALIDATE_BOOLEAN,
 
'var2' => FILTER_VALIDATE_INT
));

array_filter($input_array, function($a) { return !is_null($a) });
?>
webdesign at blackbyrd dot biz
8.10.2009 22: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)
);
mewsterus at yahoo dot com
14.09.2009 19:13
Here's an easy way to get a combination of keys and values, such that if you don't specify a key you will get the value, and if you do specify a key you will get the key:

<?php
$array
= array('One' => 'First', 'Second', 'Third', 'Four' => 'Fourth', 'Fifth');

var_dump(array_keys($array));

$names = array_filter(array_keys($array), 'is_string') + array_values($array);
ksort($array);

var_dump($names);
?>

Outputs:

array(5) {
  [0]=>string(3) "One"
  [1]=>int(0)
  [2]=>int(1)
  [3]=>string(4) "Four"
  [4]=>int(2)
}
array(5) {
  [0]=>string(3) "One"
  [1]=>string(6) "Second"
  [2]=>string(5) "Third"
  [3]=>string(4) "Four"
  [4]=>string(5) "Fifth"
}

Without using ksort, the keys appear before the fallback values, instead of inline and appearing like they replace them, however the keys are intact (which is why ksort works) so it's only execution order.
mchargue at usc dot edu
7.08.2009 23:34
Wanting to pass an additional to parameter to the callback function?  This worked for me, there's probably another way to accomplish this task but just so you see how it can be done.  (I actually used this technique to strip old dates out of an array) :

<?php
//define in global scope so functions can access
$var_to_pass = null;

function
myfilter($input_var_outer,$param) {

    global
$var_to_pass;
   
$var_to_pass = $param;

    function
mycallback($input_var_inner) {
      global
$var_to_pass;
      return (
$input_var_inner>$var_to_pass) ? true : false;
    }

   
$return_arr = array_filter($input_var_outer,'mycallback');
   
//re-key if you want
   
$return_arr = array_merge(array(),$return_arr);
    return
$return_arr;

}

$min = 5;
$a = array(1,3,5,7,9);

//remove elements from array that are not greater than $min
$a = myfilter($a,$min);

echo
"<pre>";
print_r($a);
echo
"</pre>";
?>

--

Output:
Array
(
    [0] => 7
    [1] => 9
)
chrisstocktonaz at gmail dot com
30.04.2009 18: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');
}
?>
nat at fishtrap dot co dot uk
18.03.2009 18:28
One of the nice things about this function is that you can a standard php function such as is_string

e.g.
<?php

$input
=array(1 , '2', 'three', array('sausages'));

$result = array_filter($input ,'is_string');

print_r($result);

?>

Result will be

Array
(
    [1] => 2
    [2] => three
)
Craig
7.03.2009 19:34
I wanted a function to keep the values that were filtered out and return them separately. Basically, split the array by some callback. I wrote this for the job:

<?php
function array_split($input, &$trues, &$falses, $compare)
{
    while ((
$item = array_pop($input)) != NULL)
    {
        if (
$compare($item)) $trues[] = $item;
        else
$falses[] = $item;
    }
}
?>

very simple, something I would think would be standard, and array_filter would amount to discarding the falses.
marijnk at NOSPAM dot gwobbel dot com
5.03.2009 11:16
I was looking for a function that could filter values from an array using a regular expression pattern supplied, based on leon at darkk dot net dot ru I created the following:

Description:
Return array of matching values from array using regular expression.
<?php
class array_ereg {
    function
array_ereg($pattern) { $this->pattern = $pattern; }
    function
ereg($string) {
        return
ereg($this->pattern, $string);
    }
}
?>
Usage :
<?php
      $matches
= array_filter($subject, array(new array_ereg($pattern), 'ereg'));
?>
Example:
 <?php
     $subject
= array ("Thumbs.db", "image001.png", "image001.jpg", "image002.png");
    
print_r(array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')));
?>
Outputs:
     Array ( [1] => image001.png [3] => image002.png )
niehztog
30.12.2008 10: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.12.2008 15: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
8.10.2008 20: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;
}
?>
sami
4.10.2008 8:11
Yes, it may remove NULLS, but it also removes anything that factors to a FALSE as well; like FALSE and ZERO. :/
quecoder at gmail
27.08.2008 12:00
// my implementation for array_filter 

function my_array_filter($array,$function,$preserve=true)
        {   
            $return = array();
            foreach ($array as $k=>$v)
                {
                    if($function($v)==true) $return[$k]=$v;
                }
                if($preserve) return $return;
                else return array_values($return);
        }
       
function odd($value)
        {
            return ($value & 1);
        }       
   
$oddonly = array (1,2,3,4,5,6,7,8,9);
print_r(my_array_filter($oddonly,'odd',1));   

//output    
//Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 )

//Khaled Mohammed
WASD
29.07.2008 13:53
You can easily delete all NULL elements from array with following statement:

<?php
$arr
= array_filter($arr);
?>
Joan Garnet
4.01.2008 15:47
Be careful with this function as it preserves array indexes after applying the filter:

<?php
function f( $item ){
    return
$item < 50;
}
print_r( array_filter(array( 10, 100, 20 ),"f") );
/* OUTPUT
Array
(
    [0] => 10
    [2] => 20
)*/
?>

You can easily reassign indexes like this:

<?php
function f( $item ){
    return
$item < 50;
}
print_r( array_values(array_filter(array( 10, 100, 20 ),"f")) );
/* OUTPUT
Array
(
    [0] => 10
    [1] => 20
)*/
?>
nospam at jcornelius dot com
23.10.2007 20:51
Don't forget that using callbacks in a class requires that you reference the object name in the callback like so:

<?php

$newArray
= array_filter($array, array($this,"callback_function"));

?>

Where "$this" is the reference to your object.
Martin
4.09.2007 19: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.
Hayley Watson
30.08.2007 0:49
Just a simplification of my function from last month.

<?php
function partition($input, $callback=null)
{
    if(
is_null($callback))
       
$true = array_filter($input);
    else
       
$true = array_filter($input, $callback);

   
$false = array_diff_key($input, $true);
}
?>
Hayley Watson
27.07.2007 4:31
Here is my own version of Renee Sarsoo's array_split() function; given an array and a callback it returns two arrays, in which the first contains elements that passed the filter and the second contains elements that didn't. (If no callback is passed, the first array contains the nonempty elements, as you'd get from array_filter() if you don't give it a callback). Array keys are preserved.

<?php
function partition($input, $callback=null)
{
    static
$not_empty=null;
    if(
is_null($not_empty))
       
$not_empty = create_function('$o', 'return !empty($o);');
    if(
is_null($callback)) $callback = $not_empty;

   
$true = array_filter($input, $callback);
   
$false = array_diff_key($input, $true);

    return array(
$true, $false);
}
?>
Rene Saarsoo
9.07.2007 15:07
Sometimes you want to do something with elements you have filtered out and something else with other elements. So instead of filtering elements out to one array you would like to split array into two parts:
<?php
/**
 * Splits array into two arrays using a callback function
 *
 * It is like array_filter(), but instead of one array, two arrays are returned:
 * first one with elements for which the callback function evaluates to true,
 * and second one, for which it evaluates to false.
 *
 * If no callback is supplied, all entries of input equal to FALSE will be removed.
 *
 * Array keys are preserved.
 *
 * @param $callback the callback function to use
 * @return array(truth_array, false_array)
 */
function array_split($input, $callback=null) {
   
$callback = isset($callback) ? $callback : create_function('$x', 'return $x == true;');
   
   
$true = array();
   
$false = array();
    foreach (
$input as $key => $value) {
        if (
call_user_func($callback, $value)) {
           
$true[$key] = $value;
        }
        else {
           
$false[$key] = $value;
        }
    }
   
    return array(
$true, $false);
}
?>
leon at darkk dot net dot ru
22.05.2007 21:15
Here is a way to get customizable filter

<?php
function blablabla() {
    ....
   
$new = getNewUidls();
    class
UidlFilter {
        function
UidlFilter($uidls) { $this->uidls = $uidls; }
        function
filter($metamsg) { return in_array($metamsg['uidl'], $this->uidls); }
    }
   
$msglist = array_filter($msglist, array(new UidlFilter($new), 'filter');
    ....
}
?>
klaproth at creative-mindworks dot de
23.10.2006 16:13
As long as the array's keys are irrelevant, there is a simple way to remove blank values from the array, after filtering has been applied. The following example is used to remove all strings from an array that have a length of less than 4 characters.

<?php
function validElement($element) {
    return
strlen($element) > 3;
}

$filtered_array = array_values(array_filter($input_array, "validElement"));
?>
Fladnag - bahatest at ifrance dot com
22.10.2006 18:19
If you have a form with multiple checkbox having ID element as value for selection in a list, you probably have a SQL request like :
$req="SELECT ... WHERE ID IN (".implode(',', array_keys($choices)).")";
without quote before and after choices keys because they are numeric values... but in fact, they can be string values, and a SQL injection problem.

with array_filter, you can easily filter bad values :
<?php
    $choices
=array('A'=>'on', -1=>'on', 0=>'on', 1=>'on', 12=>'on', "1)or 1=1--"=>'on');
   
print_r($choices);
   
$choices=array_filter(array_keys($choices), 'is_numeric');
   
print_r($choices);
?>
will print :
<?php
Array
(
    [
A] => on
   
[-1] => on
   
[0] => on
   
[1] => on
   
[12] => on
   
[1)or 1=1--] => on
)
Array
(
    [
1] => -1
   
[2] => 0
   
[3] => 1
   
[4] => 12
)
?>
ydotzhangatwriwindberdotorg
17.01.2006 22:57
I have written a function that will filter an array by the frequency of
element value in the array.  This may be useful to some people.

<?php
/////////////////////////////////////////////////////////////////
//    Filter an array by value freguebcy
//    Input: $array
//    cut-off: $frequency (>=1)
//    result option option: 1=$frequency and higher
//          0=$frequency only
//          -1=$frequency and lower
/////////////////////////////////////////////////////////////////
function filter_array($array, $frequency = 2, $include = 1){
   
$freg = array_count_values($array);
    if(
$frequency<1){
       print
"** frequency cut-off should be >= 1! **\n";
       return
false;
    }
    foreach(
$freg as $k => $v){
        if(
$include == 0){
            if(
$frequency != $v){
               
$freg[$k] = 0;
            }
        }elseif(
$include > 0){
            if(
$frequency > $v){
               
$freg[$k] = 0;
            }
        }else{
            if(
$frequency < $v){
               
$freg[$k] = 0;
            }
        }
    }
   
$filtered = array_filter($freg);
   
$values = array_keys($filtered);
    return
array_intersect($array,$values);
}
?>
xert
26.04.2005 14:14
According to a simple test with array_filter($array) and array_diff($array, array('')) is array_filter 2.5 times faster than array_diff when deleting empty entries.
marc dot vanwoerkom at fernuni-hagen dot de
5.07.2004 17: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.05.2004 17: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;
}
?>
steven at xinu dot org
23.02.2004 9:39
The anonymous fellow a few posts up was trying to illustrate how to use the array_filter() function with class methods but confused things a bit. Here's a cleaner example:

<?php
class testclass
{
    function
testclass()
    {
       
// define the numbers array
       
$numbers = array(1, 2, 3, 4, 5, 6);

       
// pull out the odd numbers
       
$odd = array_filter($numbers, array($this, "odd"));

       
// pull out the even numbers
       
$even = array_filter($numbers, array($this, "even"));
    }

    function
odd($var)
    {
        return(
$var % 2 == 1);
    }

    function
even($var)
    {
        return(
$var % 2 == 0);
    }
}
?>
Jeremy
29.12.2003 22:31
Here is a nice little function which will apply a callback function recursively over a multidimensional array. If the callback function returns false, then it replaces the value of the array with $filtered_ouput. This function gracefully handles objects inside of arrays (and objects within objects within arrays, etc). It is specifically designed for your callback function to process on the array key's (unlike normal array_filter which filters on the values), but it could work on the array values depending on your test criteria (YMMV).

<?PHP

function array_key_filter_multi($array, $callback, $filtered_output = "")
{
  
$ret = array();
   foreach(
$array as $key=>$value) {
       if(
$callback($key,$value)) {
           if(
is_array($value)) {
              
$ret[$key] = array_key_filter_multi($value, $callback, $filtered_output);
           }
           elseif(
is_object($value)) {
              
$ret[$key] = array_key_filter_multi(get_object_vars($value), $callback, $filtered_output);
           }
           else {   
              
$ret[$key]=$value;
           }
       }
       else {
          
$ret[$key]=$filtered_output;
       }
   }
   return
$ret;
}

?>

We use this to filter redundant data from debugging output. An example usage is:

<?

$callback_func
= create_function('$key, $value', 'return ($key == "db" || $key == "smarty") ? false : true;');
echo
"<PRE>" . print_r(array_key_filter_multi($_SESSION, $callback_func, "**filtered by function**"), true) . "</PRE>";

?>

Which filters all keys with "db" or "smarty" as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:

Array
(
    [userdata] => Array
        (
            [sid] => a130e675d380e0e9fe47897922d719ac
            [not_in_db] =>
            [user_id] => 1
            [session_id] => 154
            [permissions] => 1
            [username] => tester
        )
    [systemobjects] => Array
        (
            [db] => **filtered by function**
            [smarty] => **filtered by function**
        )
)
redshift at pandora dot be
28.06.2003 21:01
Hi all,
Here's a function that will look trough an array, and removes the array member when the search string is found.

<?php
function array_clean ($input, $delete = false, $caseSensitive = false)
    {
   
$i = 0;
    while(
$i < count($input))
        {
        if(
$delete)
            {
            if(
$caseSensitive)
                {
                if(!
strstr($input[$i] ,$delete))
                    {
                   
$return[] = $input[$i];
                    }
                }
                else
                {
                if(!
stristr($input[$i], $delete))
                    {
                   
$return[] = $input[$i];
                    }
                }
            }
            else
            {
            if(!empty(
$input[$i]))
                {
               
$return[] = $input[$i];
                }
            }
       
$i++;
        }
    return
$return;
    }
?>

array array_clean(array input [, string needle [, boolean case sensitive]])

if needle is left empty, the function will delete the array members that have no value (this means if it's empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.

Example:
$array = array("John", "Doe", "Macy");
$array = array_clean($array, "doe", false);

print_r($array);
would return:
array
(
    [0] => John
    [1] => Macy
)

Hopes this helps someone :-)
skd2 at ece dot msstate dot edu
15.05.2003 0:24
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.

11.02.2003 23:47
You cannot do this:
$non_empty_array = array_filter($original_array, 'empty');
Since empty() is not a function but a language construct. (http://www.php.net/manual/en/function.empty.php)
ajohnson at speakeasy dot org
27.09.2002 21: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.08.2002 22: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);
?>

13.06.2002 13:14
I was looking for a function able to take some values out of an array iteratively, and found array_filter very useful although i had some trouble figuring out the proper syntax...

<?php
class someclass {
    var
$current;

   
/** this is our iterative function */
   
function main ($variable,$array){
        if (
end test){
            return
true;
        }
       
$variable= some treatment...
        if (
in_array($variable, $array)){
            
$this->current=something...($variable);
           
// this is the not-well-documented part
           
$array=$array_filter($array, array($this, "array_reduce");
        }
       
$this->main($variable, $array);
    }
   
   
/** this is the function used to filter */
   
function reduce_list($var){
        return (
$var!=$this->current);
    }
}
?>
sam,pointsystems,com
21.02.2002 2:12
Here's a good function to filter multidimensional arrays:

<?php
function array_filter_multi($input, $filter="", $keepMatches=true) {
        if (!
is_array($input))
                return (
$input==$filter xor $keepMatches==false) ? $input : false;
        while (list (
$key,$value) = @each($input)){
               
$res = array_filter_multi($value, $filter,$keepMatches);
                if (
$res !== false)
                       
$out[$key] = $res;
        }
        return
$out;
}
?>

Default behavior is to remove blanks from a multi-dimensional array, but you can filter out any string (arg #2) with a positive or negative filter (arg #3).



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)