Tuesday, 08 September 2020

PHP array_filter function

PHP 

By using PHP's array_filter() function, it is easy to filter array elements.

$numbers = array(-5, -10, -2, 0, 8, 9, 16, 28);

function checkNums($value) {
    return $value > 0; 
}

$num_list = array_filter($numbers, "checkNums");

print_r($num_list);

In the above code snippet, a callback function checkNums() is created for filtering the values of the array $numbers that are bigger than 0. The filtered elements are returned into the new array $num_list and their keys are all preserved. The above code snippet will output:

Array ( [4] => 8 [5] => 9 [6] => 16 [7] => 28 ) 

If you want to reindex the array $num_list, use the function array_values().

$reindexed = array_values($num_list);
print_r($reindexed);

The output will be:

Array ( [0] => 8 [1] => 9 [2] => 16 [3] => 28 )

You can also use an anomymous function to do as the callback function checkNums() when calling array_filter(). By default, the array value will be only passed to the callback function.

$num_list = array_filter($numbers, function($value) {
    return $value > 0;
});

PHP provides a flag in the function array_filter() to control which parts of the array are sent to the callback function:

  • ARRAY_FILTER_USE_KEY: only pass the key to the callback function.
  • ARRAY_FILTER_USE_BOTH: pass both the key and the value to the callback function.


In the following example, we want to filter the fruits whose names start with letter M and the amount is larger than 10.

$fruits = array(
            "Melon" => 6,
            "Apple" => 20,
            "Banana" => 10,
            "Fig" => 8,
            "Lemon" => 15,
            "Mandarin" => 60,
            "Orange" => 33,
            "Peach" => 16,
            "Mango" => 27
        );

$filtered_fruits = array_filter($fruits, function($amount, $key) {
    return substr($key, 0, 1) === "M" && $amount > 10;
}, ARRAY_FILTER_USE_BOTH);

print_r($filtered_fruits);

The output will be:

Array ( [Mandarin] => 60 [Mango] => 27 ) 

If just want to filter the array by the key, use the constant: ARRAY_FILTER_USE_KEY:

$filtered_fruits = array_filter($fruits, function($key) {
    return $key === "Banana";
}, ARRAY_FILTER_USE_KEY);

print_r($filtered_fruits);

The above codes will filter out Banana from the array $fruits:

Array ( [Banana] => 10 ) 


Search