Home > Article > Backend Development > php-Arrays function-array_filter-use callback function to filter cells in the array_PHP tutorial
array_filter() function uses callback function to filter the cells in the array
【Function】
This function passes each value in the specified array to the callback function in turn.
If the callback function returns True, the current value of the specified array will be included in the returned result array.
Note that the key names of the array remain unchanged.
【Scope of use】
php4 > 4.0.6, php5.
【Use】
array array_filter( array input[,callback callback] )
input/required/array to perform filtering operations
callback/optional/is the specified callback function
【Example】
[php]
//Define callback function
function odd( $var )
{
return ( $var%2 == 1);
}
function even( $var )
{
return ( $var%2 == 0 );
}
//Define two arrays respectively
$array1 = array( "blue" => 6, "red" => 2, "green" => 3, "purple" => 4 );
$array2 = array( "green" => 5, "blue" => 6, "yellow" =>7, "cyan" => 8 );
echo "Filter odd numbers: n";
print_r( array_filter( $array1, "odd" ) );
echo "Filter even numbers:n";
print_r( array_filter( $array2, "even" ) );
/*
Filter odd numbers:
Array
(
[green] => 3
)
Filter even numbers:
Array
(
[blue] => 6
[cyan] => 8
)
*/
Excerpted from zuodefeng’s notes