Home  >  Article  >  Backend Development  >  The role of the array_filter() function in PHP is to filter the elements in the array and return the filtered new array

The role of the array_filter() function in PHP is to filter the elements in the array and return the filtered new array

WBOY
WBOYforward
2023-09-17 11:33:051288browse

The role of the array_filter() function in PHP is to filter the elements in the array and return the filtered new array

The array_filter() function filters the elements of an array using a user-created callback function. It returns the filtered array.

Syntax

array_filter(arr, callback, flag)

Parameters

  • arr - The array to be filtered

  • callback - The callback function to use

  • flag - Parameters sent to the callback function:

    >
    • ARRAY_FILTER_USE_KEY - Pass the key as the only argument to the callback instead of the value

    • ARRAY_FILTER_USE_BOTH - Pass both the value and the key as arguments Passed to the callback instead of the value

Returns

array_filter() function returns the filtered array.

Example

Real-time demonstration

<?php
function check($arr) {
   return(!($arr & 1));
}
$arr1 = array(3, 6, 9, 15, 20, 30, 45, 48, 59, 66);
print_r(array_filter($arr1, "check"));
?>

Output

Array
(
[1] => 6
[4] => 20
[5] => 30
[7] => 48
[9] => 66
)

The above is the detailed content of The role of the array_filter() function in PHP is to filter the elements in the array and return the filtered new array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete