Home > php教程 > php手册 > body text

php-Arrays函数-array_filter-用回调函数过滤数组中的单元

WBOY
Release: 2016-06-13 10:49:44
Original
1171 people have browsed it

array_filter() 函数 用回调函数过滤数组中的单元

【功能】
         该函数依次将指定数组中的每个值传递到回调函数。
         如果回调函数返回True,则指定数组的当前值会被包含在返回的结果数组中。
         注意数组的键名保持不变。
【使用范围】
         php4 > 4.0.6、php5.
【使用】
         array array_filter( array input[,callback callback]  )
         input/必需/执行过滤操作的数组
         callback/可选/为指定的回调函数
【示例】
[php]
//定义回调函数 
function odd( $var ) 

        return ( $var%2 == 1); 

 
function even( $var ) 

        return ( $var%2 == 0 ); 

//分别定义两个数组 
$array1 = array( "blue" => 6, "red" => 2, "green" => 3, "purple" => 4 ); 
$array2 = array( "green" => 5, "blue" => 6, "yellow"=>7, "cyan" => 8 ); 
echo "过滤奇数:\n"; 
print_r( array_filter( $array1, "odd" ) ); 
echo "过滤偶数:\n"; 
print_r( array_filter( $array2, "even" ) ); 
/*
过滤奇数:
Array
(
    [green] => 3
)
过滤偶数:
Array
(
    [blue] => 6
    [cyan] => 8
)
*/ 

 


摘自 zuodefeng的笔记

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!