php

PHP array_filter() function

The data of the array can be filtered by iterating the array elements with the loop in PHP. This task can be done very easily using the array_filter() function. The user-defined callback function is used in this function to filter the data. The array returned by this function preserved the key of the original array. Different uses of the array_filter() function have been shown in this tutorial.

Syntax:
The syntax of the array_filter() is given below.

array array_filter($array, $callback_function, $flag)

  • The first argument of the function is mandatory and contains an array and will be used for filtering.
  • The second argument is optional, and it is a callback function used to filter the array data.
  • The third argument is optional, and it can store two types of values. One value is ARRAY_FILTER_USE_KEY which passes the key of the array as the argument in the callback function. Another value can be ARRAY_FILTER_USE_BOTH, which passes both key and value as the callback function’s argument.
  • It returns the filtered array.

Different uses of array_filter() functions have been shown in the next part of the tutorial.

Example-1: Filter a numeric array

Create a PHP file with the following script to filter the array values based on a condition. The array declared in the script contains positive, negative, and zero values. The array_filter() function has been used in the script to retrieve the negative values from the array. Next, the filtered array was printed.

<?php
//Declare a numeric array of positive, negative, and zero numbers
$array = [78, -56, 45, 0, -33, 59, -21];

//Create a new array of negative numbers
$filter_array = array_filter($array,
    function ($a) {
        return $a < 0;
    }
);

//Print the new array
echo "Negative numbers of the array are:<br />";
foreach($filter_array as $value){
  echo $value."<br />";
}

Output:
The following output will appear after executing the above script.

Example-2: Filter an associative array

Create a PHP file with the following script to filter the associative array values based on a condition. The array contains the student’s name as the key and the mark as the value. The array_filter() function has been used in the script to retrieve those elements from the array where the value is more than 79. Next, the filtered array was printed.

<?php
//Declare an associative array of four elements
$marks = ["Mir Ali"=>90, "Kamal Hossain"=>78, "Sakil Ahamed"=>82 , "Moniruzzaman"=>85];

//Create a new array that contains number more than 79
$filter_marks = array_filter($marks,
    function ($mark) {
        return $mark > 79;
    }
);

//Print the new array
foreach($filter_marks as $key => $value) {
  echo $key. " obtained ".$value."<br>";
}

Output:
The following output will appear after executing the above script.

Example-3: Filter an associative array using an object

Create a PHP file with the following script that will filter the values of an array by using the class object in the callback function. The associative array contains the applicant id as key and ‘Present’ or ‘Absent’ as value. The array_filter() function will filter those elements where the values are ‘Present’.

<?php
/*Declare a class to find out the present applicants
 * by using a method*/

class check
{
    public function Present($val)
    {
        return $val == "Present";
    }
}

//Declare an associative array of 5 elements
$applicants = ['08967'=>'Present', '04567'=>'Absent', '08923'=>'Present', '03412'=>'Absent', '07811'=>'Present'];

/*Create a new array by using array_filter()
 with the object and callback function*/

$present_applicants = array_filter($applicants,
    [new check(), 'Present']
);

//Print the number of total applicants
echo "Total applicants = ".count($applicants)."<br />";
//Print the number of present applicants
echo "Present applicants = ".count($present_applicants);

Output:
The following output will appear after executing the above script.

Example-4: Filter an associative array using a flag

Create a PHP file with the following script to filter the array based on the ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH flags. The first array_filter() function will retrieve the element from the array where the key value is ‘London’. The second array_filter() function will retrieve the element from the array where the key value is ‘Kabul’, and the value is ‘Afghanistan’.

<?php
//Declare an associative array
$array = ['Dhaka' => 'Bangladesh','Kabul' => 'Afghanistan','Canberra' => 'Australia',
          'Beijing' => 'China', 'London' => 'England', 'Washington D.C.' => 'United States'];

//Using array_filter() with ARRAY_FILTER_USE_KEY
$filtered_array1 = array_filter(
    $array,
    fn ($k) => $k == 'London', ARRAY_FILTER_USE_KEY);

//Print the value of the filtered array
foreach($filtered_array1 as $key => $value) {
  echo "<br />Country Name: $value<br />";
  echo "Capital Name. $key<br />";
}

//Using array_filter() with ARRAY_FILTER_USE_BOTH
$filtered_array2 = array_filter(
    $array,
    fn ($v, $k) => $k == 'Kabul' && $v == 'Afghanistan', ARRAY_FILTER_USE_BOTH);

//Print the value of the filtered array
foreach($filtered_array2 as $key => $value) {
  echo "<br />Country Name: $value<br />";
  echo "Capital Name. $key<br />";
}

Output:
The following output will appear after executing the above script.

Example-5: Filter a multi-dimensional array

Create a PHP file with the following script that will filter the values of the two-dimensional array. The array_filter() function will filter those values from the array where the value of the salary key is greater than 60000.

<?php
//Declare an two-dimensional array
$employees = [
  ['name' => 'Jafar Iqbal','email' => '[email protected]', 'salary' => 60000],
  ['name' => 'Mohammed Ali','email' => '[email protected]', 'salary' => 55000],
  ['name' => 'Nila Akter','email' => '[email protected]', 'salary' => 73000],
  ['name' => 'Riya Chowdhury','email' => '[email protected]', 'salary' => 80000]];

//Filter the array values based on salary
$filterred_employees = array_filter($employees, function($array){
  //Return employees whose salary is more than 60000
  if($array['salary'] > 60000){
    return $array;
  }
});

//Print the filtered array
echo '<pre>';
print_r($filterred_employees);
echo '</pre>';
?>

Output:
The following output will appear after executing the above script.

Conclusion:

The array_filter() function can filter the array values differently by using the callback function with or without the flag value. The ways of filtering numeric and associative one-dimensional and two-dimensional arrays have been shown in the examples of this tutorial. I hope the PHP users will be able to filter the values based on their requirements after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.