PHP: array_filter() function
PHP: Filters elements of an array using a callback function
The array_filter() function passes each value of a given array to a user defined function. If the user defined function allows, the current value from the array is returned into the result array.
Note: The function Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from the array is returned into the result array. Array keys are preserved.
Version:
(PHP 4 and above)
Syntax:
array_filter(input_array, user_defined_function)
Parameter:
Name | Description | Required / Optional |
Type |
---|---|---|---|
input_array | The input array. | Required | Array |
user_defined_function | The user defined function. If no user-defined function is supplied, all entries of input array equal to FALSE. | Required | - |
Return value:
The filtered array.
Value Type: Array
Example:
<?php
function my_function($item_values)
{
if ($item_values>100)
{
return true;
}
return false;
}
$item_list=array("Item1" => 100, "Item2" => 200, "Item3" => 125, "Item4" => 100);
print_r(array_filter($item_list,"my_function"));
?>
Output:
Array ( [Item2] => 200 [Item3] => 125 )
Pictorial Presentation:

View the example in the browser
Practice here online :
See alsoPrevious:array_fill
Next: array_flip
PHP: Tips of the Day
Checks if two numbers are approximately equal to each other
Example:
<?php function tips_approximatelyEqual($number1, $number2, $epsilon = 0.001) { return abs($number1 - $number2) < $epsilon; } print(tips_approximatelyEqual(15.0, 15.00001)); print(tips_approximatelyEqual(15.0, 15.01)); ?>
Output:
1
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework