(PHP 4 >= 4.0.6, PHP 5)
array_filter — 用回调函数过滤数组中的单元
array_filter() 依次将
input
数组中的每个值传递到
callback
函数。如果
callback
函数返回 TRUE
,则
input
数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。
Example #1 array_filter() 例子
<?php
function odd($var)
{
return($var % 2 == 1);
}
function even($var)
{
return($var % 2 == 0);
}
$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"));
?>
以上例程会输出:
Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 )
用户不应在回调函数中修改数组本身。例如增加/删除单元或者对 array_filter() 正在作用的数组进行 unset。如果数组改变了,此函数的行为没有定义。
如果没有提供 callback
函数, array_filter()
将删除 input
中所有等值为
FALSE
的条目。更多信息见转换为布尔值。
Example #2 array_filter() 无
callback
<?php
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
以上例程会输出:
Array ( [0] => foo [2] => -1 )
input
The array to iterate over
callback
The callback function to use
If no callback
is supplied, all entries of
input
equal to FALSE
(see
converting to
boolean) will be removed.
Returns the filtered array.
Example #3 array_filter() example
<?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"));
?>
以上例程会输出:
Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 )
Example #4 array_filter() without
callback
<?php
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
以上例程会输出:
Array ( [0] => foo [2] => -1 )
If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined.