Home  >  Article  >  Backend Development  >  PHP uses the callback function to filter the elements in the array function array_filter()

PHP uses the callback function to filter the elements in the array function array_filter()

黄舟
黄舟Original
2017-11-07 13:26:271532browse

Example

Use callback functionFilter elements in array:

<?php
function test_odd($var)
{
return($var & 1);
}

$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>

Definition and usage

array_filter() The function uses a callback function to filter the elements in the array.

This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.

Syntax

array_filter(array,callbackfunction);
Parameters Description
array Required. Specifies the array to filter.
callbackfunction Required. Specifies the callback function to be used.

Technical details

Return value: Returns the filtered array.
PHP version: 4.0.6+

Looking through the manual todayQuery# When using the details of ##array_filter(), I saw a small key point: If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed. If no callback function is given, all entries of input equal to FALSE (see converting to boolean) will be removed. FALSE elements will be removed. Isn't this useful for filtering arrays with empty elements? Quickly write an example to test the idea:

$entry = array( 
             0 => &#39;蓝色夏威夷的博客&#39;, 
             1 => false, 
             2 => 1, 
             3 => null, 
             4 => &#39;&#39;, 
             5 => &#39;http://www.jb51.net&#39;, 
             6 => &#39;0&#39;,
             7 => array(),
             8 => 0
          );
$validarr = array_filter($entry);
print_r($validarr);
//输出结果:
Array
(
    [0] => 蓝色夏威夷的博客
    [2] => 1
    [5] => http://www.jb51.net
)

Some array elements that can be converted to Boolean FALSE have been removed, which makes a very comprehensive filter for us to get a valid array. .

The above is the detailed content of PHP uses the callback function to filter the elements in the array function array_filter(). For more information, please follow other related articles on the PHP Chinese website!

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