In PHP, array_filter() is a very practical function that can be used to filter elements in an array, retaining only elements that meet the criteria. It is usually used in conjunction with callback functions, and in many practical applications, using global functions (such as is_numeric ) to filter data is a concise and efficient way.
This article will use examples to demonstrate how to use array_filter() with is_numeric to filter numeric elements in an array.
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
$array : Enter the array.
$callback : A callback function used to determine whether each element is retained.
$mode : Filter mode, optional.
If the callback function is not provided, array_filter() will remove all values equivalent to false by default (such as false , 0 , "" , null , etc.).
$items = ['apple', 42, '123', null, 0, 'banana', 3.14, '0', true];
$numericItems = array_filter($items, 'is_numeric');
print_r($numericItems);
Array
(
[1] => 42
[2] => 123
[6] => 3.14
[7] => 0
)
As you can see, array_filter() retains all elements in the array that are judged as numeric values by is_numeric . This includes integers, floating point numbers, numeric strings (such as '123' ), and even string '0' .
You can also use is_numeric with other conditions, for example:
$items = ['apple', 42, '123', null, 0, 'banana', 3.14, '0', true];
// Only retain greater than 10 The value of
$filtered = array_filter($items, function ($item) {
return is_numeric($item) && $item > 10;
});
print_r($filtered);
Array
(
[1] => 42
[2] => 123
)
For example, suppose your website (such as https://m66.net/form-handler.php ) receives an array of data that contains user input, which may contain text, null values, or numbers. You want to extract only numbers for statistics or verification, and you can quickly complete this task with array_filter() and is_numeric() .
array_filter() can be used to filter array elements.
It is very simple and efficient when used with global functions such as is_numeric .
Complex filtering can be performed through further combination logic through anonymous functions.
Mastering this technique can make your PHP code more flexible and powerful in data processing.
Related Tags:
array_filter