Tác dụng của hàm array_filter()
The array_filter()
function filters the elements of an array using a callback function.
The following table summarizes the technical details of this function.
Return Value: | Returns the filtered array. |
---|---|
Changelog: | The optional flag parameter was added in PHP 5.6.0 |
Version: | PHP 4.0.6+ |
Syntax
The basic syntax of the array_filter()
function is given with:
The following example shows the array_filter()
function in action.
Example
Run this code »<?php
// Defining callback function
function even($num){
if($num % 2 == 0){
return true;
}
}
// Sample array
$numbers = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
// Filtering numbers array
$result = array_filter($numbers, "even");
print_r($result);
?>
Parameters
The array_filter()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to filter. |
callback | Optional. Specifies the name of the callback function. |
flag |
Optional. Specifies what arguments are sent to callback:
Default is
0 which will pass value as the only argument to callback function. |
More Examples
Here're some more examples showing how array_filter()
function actually works:
In following example this function returns all the values from the numbers array whose keys are greater than the character "b" using the flag parameter:
Example
Run this code »<?php
// Sample array
$numbers = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
// Filtering numbers array using key
$result = array_filter($numbers, function($key){
return $key > "b";
}, ARRAY_FILTER_USE_KEY);
print_r($result);
?>
In the following example this function returns the even values whose keys are greater than "b".
Example
Run this code »<?php
// Sample array
$numbers = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
// Filtering numbers array using key and value
$result = array_filter($numbers, function($value, $key){
return $key > "b" && !($value & 1);
}, ARRAY_FILTER_USE_BOTH);
print_r($result);
?>