Open In App

PHP array_filter() Function

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This built-in function in PHP is used to filter the elements of an array using a user-defined function which is also called a callback function. The array_filter() function iterates over each value in the array, passing them to the user-defined function or the callback function. If the callback function returns true then the current value of the array is returned into the result array otherwise not. This way the keys of the array gets preserved, i.e. the key of element in the original array and output array are same.

Syntax:

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

Parameters: The function takes three parameters, out of which one is mandatory and the other two are optional.

  1. $array (mandatory): This refers to the input array on which the filter operation is to be performed.
  2. $callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed.
  3. $flag (optional): Refers to the arguments passed to the callback function.
    • ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.
    • ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value.

Return Value: The function returns a filtered array.

Below is a program showing how to return or filter out even elements from an array using array_filter() function.




<?php
  
// PHP function to check for even elements in an array
function Even($array)
{
    // returns if the input integer is even
    if($array%2==0)
       return TRUE;
    else 
       return FALSE; 
}
  
$array = array(12, 0, 0, 18, 27, 0, 46);
print_r(array_filter($array, "Even"));
  
?>


Output:

Array
(
    [0] => 12
    [1] => 0
    [2] => 0
    [3] => 18
    [5] => 0
    [6] => 46
)

In this example, we will not pass the callback function and let’s see the output. We will see that the 0 or false elements are not printed:




<?php
  
// PHP function to check for even elements in an array
function Even($array)
{
    // returns if the input integer is even
    if($array%2==0)
       return TRUE;
    else 
       return FALSE; 
}
  
$array = array(12, 0, 0, 18, 27, 0, 46);
print_r(array_filter($array));
  
?>


Output:

Array
(
    [0] => 12
    [3] => 18
    [4] => 27
    [6] => 46
)

Reference: http://php.net/manual/en/function.array-filter.php



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads