English | 简体中文 | 繁體中文
查询

Ds\Set::filter()函数—用法及示例

「 过滤集合中的元素,并返回一个新的集合 」


Ds\Set::filter() 是 PHP Data Structures (Ds) 扩展中的一个方法,它用于过滤集合中的元素,并返回一个新的集合。

适用版本: PHP 7.2 及以上版本

语法:

public Ds\Set Ds\Set::filter ( callable $callback )

参数:

  • callback:一个回调函数,函数原型为 bool function($value): bool,用于进行元素过滤。如果回调函数返回 true,则保留元素;如果返回 false,则过滤掉元素。

返回值: 返回一个新的 Ds\Set 对象,其中包含通过回调函数过滤保留的元素。

示例:

// 创建一个 Set
$set = new Ds\Set([1, 2, 3, 4, 5]);

// 使用 filter 方法过滤偶数
$filteredSet = $set->filter(function($value) {
    return $value % 2 == 0;
});

// 输出过滤后的集合
print_r($filteredSet);

输出:

Ds\Set Object
(
    [0] => 2
    [1] => 4
)
补充纠错
上一个函数: Ds\Set::diff()函数
下一个函数: Ds\Set::first()函数
热门PHP函数
分享链接