note 99073 added to function.array-filter
| From: | acid24 at gmail dot com | Date: | Mon, 26 Jul 2010 12:58:31 +0000 |
| Subject: | note 99073 added to function.array-filter | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171126@lists.php.net to get a copy of this message | ||
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)
}
----
Server IP: 69.147.83.197
Probable Submitter: 193.105.64.1
----
Manual Page -- http://www.php.net/manual/en/function.array-filter.php
Edit -- https://master.php.net/note/edit/99073
Del: integrated -- https://master.php.net/note/delete/99073/integrated
Del: useless -- https://master.php.net/note/delete/99073/useless
Del: bad code -- https://master.php.net/note/delete/99073/bad+code
Del: spam -- https://master.php.net/note/delete/99073/spam
Del: non-english -- https://master.php.net/note/delete/99073/non-english
Del: in docs -- https://master.php.net/note/delete/99073/in+docs
Del: other reasons-- https://master.php.net/note/delete/99073
Reject -- https://master.php.net/note/reject/99073
Search -- https://master.php.net/manage/user-notes.php