Hướng dẫn
Quảng cáo

Hàm array_filter() trong PHP

Hướng dẫn cách sử dụng hàm array_filter() về mảng trong lập trình PHP

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:

array_filter(array, callback, flag);

The following example shows the array_filter() function in action.

<?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:

  • ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of value.
  • ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value.
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:

<?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".

<?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);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements