欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > php >内容正文

php

PHP array_filter()函数与示例

发布时间:2025/3/11 php 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 PHP array_filter()函数与示例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

PHP array_filter()函数 (PHP array_filter() Function)

array_filter() function is used to apply a filter on array elements based on the function and returns the array with filtered elements, it accepts an array to be checked and a callback function. The callback function is used to validate the elements in the array.

array_filter()函数用于基于该函数在数组元素上应用过滤器,并返回带有已过滤元素的数组,它接受要检查的数组和回调函数。 回调函数用于验证数组中的元素。

Syntax:

句法:

array_filter(array,callback_function) : array

Here,

这里,

  • array is the input array in which we have to apply the filter.

    数组是我们必须在其中应用过滤器的输入数组。

  • callback_function is the function, in which we write the condition to be validated.

    callback_function是函数,我们在其中编写要验证的条件。

Examples:

例子:

Input:$arr = array(10, 20, -10, -20, 50, 0);//here we have to filter the positive numbers //the callback function to check the positive number is "isPositive()"Function calling: $temp = array_filter($arr, "isPositive");Output:Array([0] => 10[1] => 20[4] => 50)So, here 0th , 1st and 4th elements are positive

PHP code 1: Find the positive number from given array of the numbers.

PHP代码1:从给定的数字数组中找到正数。

<?php//function to check wheather number is positive or notfunction isPositive($val){if($val>0)return $val;}// array $arr = array(10, 20, -10, -20, 50, 0);// array with only positive value$temp = array_filter($arr, "isPositive");print_r ($temp);?>

Output

输出量

Array ([0] => 10[1] => 20[4] => 50 ) .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}

PHP code 2: Find the persons who are eligible for voting from given array of persons

PHP代码2:从给定的一组人员中找到有资格投票的人员

Here, we also have the "keys" and based on the age key we are checking the voting eligibility.

在这里,我们还有“键”,并且根据年龄键,我们正在检查投票资格。

<?php//function to check wheather person is eligible//for voting or not?function isVoter($val){if($val['age']>=18)return $val;}// person's array $arr = array(array("name" => "Prem", "age" => 28,"city" => "Gwalior",),array("name" => "Manju", "age" => 25,"city" => "Gwalior",),array("name" => "Radib Kar", "age" => 23,"city" => "Chennai",),array("name" => "Prerana", "age" => 17,"city" => "Gwalior",),);// array with voting eligible persons$temp = array_filter($arr, "isVoter");print_r ($temp);?>

Output

输出量

Array ([0] => Array([name] => Prem[age] => 28 [city] => Gwalior)[1] => Array ([name] => Manju [age] => 25 [city] => Gwalior)[2] => Array ([name] => Radib Kar [age] => 23 [city] => Chennai))

翻译自: https://www.includehelp.com/php/array_filter-function-with-example.aspx

创作挑战赛新人创作奖励来咯,坚持创作打卡瓜分现金大奖

总结

以上是生活随笔为你收集整理的PHP array_filter()函数与示例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。