Blogger Information
Blog 9
fans 0
comment 0
visits 5811
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP array_filter()函数:过滤数组中的(空)值
系统开发-Wu Manager
Original
864 people have browsed it

array_filter() 函数根据回调函数过滤数组中的值,省略回调函数则默认过滤空值。
array_filter()
语法:
code
array_filter( array[, function] )

省略回调函数过滤数组单元空值的例子
code
<?php
$array = array(
0 => ‘我爱开发网’,
1 => ‘www.5idev.com’,
2 => null,
3 => 1,
4 => ‘’,
5 => false,
6 => ‘0’
);
print_r(array_filter($array));
?>

运行该例子输出:
code
Array
(
[0] => 我爱开发网
[1] => www.5idev.com
[3] => 1
)
过滤的空值,与empty()函数对应,具体包括:0,’0’,’’,false,array(),null等,具体参见:《PHP empty() 检测一个变量是否为空》一文。
使用回调函数过滤指定值
code
$array = array(
0 => ‘www.5idev.com’,
1 => 1,
2 => 6,
3 => ‘’,
4 => false,
5 => 0,
6 => -6,
7 => ‘8’
);
function filter($v){
if( is_int($v) && $v % 2 == 0 ){
return true;
} else {
return false;
}
}
print_r(array_filter($array,”filter”));
运行该例子输出:
code
Array
(
[2] => 6
[5] => 0
[6] => -6
)
如果有回调函数,array_filter函数会依次将数组单元的值传递到回调函数,如果回调函数返回true,则该单元会被保留,反之则该数组单元则会被删除。
注意,如果被过滤的数组是关联数组,键名会保持不变。array_filter操作的是原数组的一个副本,如果要想改变原数组,则需要重新赋值:
code
$array = array_filter($array);

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post