Php-Arrays function-array_filter-filter elements in the array using the callback function

Source: Internet
Author: User

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

[Function]
This function transmits each value in the specified array to the callback function in sequence.
If the callback function returns True, the current value of the specified array is included in the returned result array.
Note that the key name of the array remains unchanged.
Scope of use]
Php4> 4.0.6, php5.
[Use]
Array array_filter (array input [, callback])
Input/required/array for filtering
Callback/optional/specifies the callback function
[Example]
[Php]
<? Php
// Define the 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 values:
Array
(
[Green] => 3
)
Filter even numbers:
Array
(
[Blue] => 6
[Cyan] => 8
)
*/

 


Taken from zuodefeng's note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.