Home  >  Article  >  Backend Development  >  php-Arrays function-array_filter-use callback function to filter cells in the array_PHP tutorial

php-Arrays function-array_filter-use callback function to filter cells in the array_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:51:15945browse

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478205.htmlTechArticlearray_filter() function uses the callback function to filter the units in the array [Function] This function sequentially filters each element in the specified array. value is passed to the callback function. If the callback function returns True, it means...
Statement:
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