1: 有回调函数
<?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"));
?>
output:
Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)
2: 无回调函数
<?php
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
output:
Array
(
[0] => foo
[2] => -1
)
3: 第二个参数直接写回调函数(实现)
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
)
4: (OOP)类中的应用
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.