In PHP, array_filter() is a very practical function that can filter elements in an array with customization. By passing in a callback function, we can retain or remove elements from the array based on specific logical conditions. In this article, we will explain how to use array_filter() to filter out all integer terms in an array.
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
$array : The original array that needs to be filtered.
$callback : A callback function used to determine whether each element is retained. Return true means reserved, and false means culling.
$mode : Optional parameter to control the parameters (key, value, or key-value pair) of the incoming callback function.
If $callback is not provided, elements with a value of false will be filtered by default (such as 0 , empty string, null , etc.).
Suppose we have an array containing various types of data, such as strings, floating point numbers, boolean values, and integers. We want to keep only integers.
<?php
$data = [1, '2', 3.5, 4, 'hello', true, 0, null, 7, '8'];
$integers = array_filter($data, function ($item) {
return is_int($item);
});
print_r($integers);
?>
Array
(
[0] => 1
[3] => 4
[8] => 7
)
As you can see, only the real integers in the array are preserved, while '2' (string) or 3.5 (floating point numbers) are filtered out.
By default, array_filter() retains the key index of the original array. If you want to reindex, you can use array_values() :
$integers = array_values(array_filter($data, function ($item) {
return is_int($item);
}));
This filtering method is very useful in actual development. For example, when you get a mixed data array from a user input or remote API, you can use array_filter() to quickly process it when you need to type validation or data cleaning.
for example:
// Simulate data obtained from remote interfaces
$response = json_decode(file_get_contents("https://api.m66.net/data"), true);
$cleaned = array_filter($response['values'], function ($value) {
return is_int($value);
});
In this code, after we get the data from https://api.m66.net/data , we use array_filter() to eliminate non-integer values.
array_filter() is a powerful array processing function in PHP. It can implement various custom filtering logic with callback functions. Through it, we can easily extract the required elements from the array, such as integers, strings, or data that complies with specific rules.
Remember, using it with built-in type detection function like is_int() can make your data cleaner and more reliable, and also make your code more elegant.
If you have more needs to deal with arrays, functions such as array_map() and array_reduce() are also very worth a try!