PHP array_filter() examples

Last updated on February 22, 2022 A Goodman Loading... Post a comment

The array_filter() function in PHP, as its name so precisely explains, is used to filter elements of an input array using a callback function.

Syntax:

array_filter(array, callback, flag)

The flag argument is optional. Its default value is 0 and will pass the value as the only argument to the callback. If the flag is set to ARRAY_FILTER_USE_KEY, only array keys are sent to the callback. Otherwise, when the flag is given the value of ARRAY_FILTER_USE_BOTH, both array keys and values are sent to the callback.

Examples

Example 1: Basic

We have a simple array that contains the names of some animals. Our goal is to get an array of animals whose name is more than 3 characters.

Code:

<?php
$arr_input = ['Dog', 'Cat', 'Monkey', 'Chicken', 'Dragon', 'Alligator'];

$arr_output = array_filter($arr_input, function($item){
  // return animal whose name is more than 3 characters
  if(strlen($item) > 3){
    return $item;
  }
});

// Printing the output
echo '<pre>';
print_r($arr_output);
echo '</pre>';
?>

Output:

Array
(
    [2] => Monkey
    [3] => Chicken
    [4] => Dragon
    [5] => Alligator
)

Example 2: Filtering a multi-dimensional array

Assume we have an array of people and want to filter out everyone who is older than 10 years old.

Code:

<?php
// the input array contains information of people, including their names and ages
$arr_input = [
  [
    'name' => 'Ann',
    'age' => 33
  ],
  [
    'name' => 'Max',
    'age' => 11
  ],
  [
    'name' => 'John',
    'age' => 45
  ],
  [
    'name' => 'Trump',
    'age' => 5
  ],
  [
    'name' => 'Pompeo',
    'age' => 6
  ]
];

$arr_output = array_filter($arr_input, function($item){
  // return everybody who is older than 10
  if($item['age'] > 10){
    return $item;
  }
});

// Printing the output
echo '<pre>';
print_r($arr_output);
echo '</pre>';
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Ann
            [age] => 33
        )

    [1] => Array
        (
            [name] => Max
            [age] => 11
        )

    [2] => Array
        (
            [name] => John
            [age] => 45
        )

)

I hope the above PHP array filter examples are helpful for you. The PHP official doc is a good place to look up more detailed information.

Further reading:

I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles