Home > Backend Development > PHP Tutorial > 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
Release: 2023-09-17 11:34:01
forward
1296 people have browsed it

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)
Copy after login

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"));
?>
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template