array_all / array_any / array_find …

array_all(array $array, callable $callback): bool — array_any(array $array, callable $callback): bool — array_find(array $array, callable $callback): mixed — array_find_key(array $array, callable $callback): mixed — array_first(array $array): mixed — array_last(array $array): mixed

PHP 8.4 现代化回调四件套(array_all/array_any/array_find/array_find_key,回调收值与键、短路返回)与 8.5 的 array_first/array_last 一次讲透,对照各语言原生等价物。

C C23

C23
#include <stdio.h>

/* 手写对照版:谓词接收(值,下标) */
static int all(const int *xs, int n, int (*pred)(int, int)) {
    for (int i = 0; i < n; i++) {
        if (!pred(xs[i], i)) return 0;
    }
    return 1;
}
static int any(const int *xs, int n, int (*pred)(int, int)) {
    for (int i = 0; i < n; i++) {
        if (pred(xs[i], i)) return 1;
    }
    return 0;
}
/* 返回首个命中项的下标,找不到返回 -1(充当 array_find_key 的对应物) */
static int find(const int *xs, int n, int (*pred)(int, int)) {
    for (int i = 0; i < n; i++) {
        if (pred(xs[i], i)) return i;
    }
    return -1;
}

static int gt40(int v, int i) { (void)i; return v > 40; }
static int lt50(int v, int i) { (void)i; return v < 50; }
static int gt80(int v, int i) { (void)i; return v > 80; }

int main(void) {
    int xs[] = {92, 47, 88};
    int n = (int)(sizeof xs / sizeof xs[0]);
    int idx = find(xs, n, gt80);
    printf("%d\n", all(xs, n, gt40));
    printf("%d\n", any(xs, n, lt50));
    printf("%d\n", idx >= 0 ? xs[idx] : -1);
    printf("%d\n", idx);
    printf("%d\n", xs[0]);
    printf("%d\n", xs[n - 1]);
    return 0;
}
输出
1
1
92
0
92
88

C++ C++26

C++26
#include <iostream>
#include <vector>

/* 手写对照版:lambda 谓词 */
template <typename F>
static bool all(const std::vector<int>& xs, F pred) {
    for (int x : xs) {
        if (!pred(x)) return false;
    }
    return true;
}
template <typename F>
static bool any(const std::vector<int>& xs, F pred) {
    for (int x : xs) {
        if (pred(x)) return true;
    }
    return false;
}

int main() {
    std::vector<int> xs = {92, 47, 88};
    std::cout << std::boolalpha;
    std::cout << all(xs, [](int v) { return v > 40; }) << "\n";
    std::cout << any(xs, [](int v) { return v < 50; }) << "\n";
    for (size_t i = 0; i < xs.size(); i++) {
        if (xs[i] > 80) { // 首个命中:先值后下标
            std::cout << xs[i] << "\n" << i << "\n";
            break;
        }
    }
    std::cout << xs.front() << "\n"; // array_first
    std::cout << xs.back() << "\n";  // array_last
    return 0;
}
输出
true
true
92
0
92
88

C# v11.0.100

v11.0.100
// LINQ 即原生对应物:All/Any/First(谓词) 对照 PHP 四件套,
// First()/Last() 即 array_first/array_last
var scores = new[]
{
    KeyValuePair.Create("alice", 92),
    KeyValuePair.Create("bob", 47),
    KeyValuePair.Create("carol", 88),
};
Console.WriteLine(scores.All(p => p.Value > 40));
Console.WriteLine(scores.Any(p => p.Value < 50));
Console.WriteLine(scores.First(p => p.Value > 80).Value);
Console.WriteLine(scores.First(p => p.Value > 80).Key);
Console.WriteLine(scores[0].Value);
Console.WriteLine(scores[^1].Value);
输出
True
True
92
alice
92
88

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
	// Go 标准库无泛型查找:手写循环
	keys := []string{"alice", "bob", "carol"} // 固定键序保证确定性
	scores := map[string]int{"alice": 92, "bob": 47, "carol": 88}
	all, any := true, false
	for _, v := range scores { // all/any 结果与遍历顺序无关
		if v <= 40 {
			all = false
		}
		if v < 50 {
			any = true
		}
	}
	findVal, findKey := 0, ""
	for _, k := range keys { // 「首个匹配」必须按固定键序
		if scores[k] > 80 {
			findVal, findKey = scores[k], k
			break
		}
	}
	fmt.Println(all)
	fmt.Println(any)
	fmt.Println(findVal)
	fmt.Println(findKey)
	fmt.Println(scores[keys[0]])
	fmt.Println(scores[keys[len(keys)-1]])
}
输出
true
true
92
alice
92
88

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new LinkedHashMap<>();
        scores.put("alice", 92);
        scores.put("bob", 47);
        scores.put("carol", 88);
        System.out.println(scores.values().stream().allMatch(v -> v > 40));
        System.out.println(scores.values().stream().anyMatch(v -> v < 50));
        System.out.println(scores.values().stream().filter(v -> v > 80).findFirst().orElse(null));
        System.out.println(scores.entrySet().stream().filter(e -> e.getValue() > 80).findFirst().map(Map.Entry::getKey).orElse(null));
        var vals = scores.values().stream().toList(); // 流没有 first/last
        System.out.println(vals.get(0));
        System.out.println(vals.get(vals.size() - 1));
    }
}
输出
true
true
92
alice
92
88

JavaScript v26.13.1

v26.13.1
// JS 原生最全:every/some/find/findIndex 外加 at()
const scores = { alice: 92, bob: 47, carol: 88 };
const vals = Object.values(scores);
console.log(vals.every((v) => v > 40));
console.log(vals.some((v) => v < 50));
console.log(vals.find((v) => v > 80));
console.log(vals.findIndex((v) => v > 80));
console.log(vals.at(0)); // array_first
console.log(vals.at(-1)); // array_last
输出
true
true
92
0
92
88

PHP v8.6.0

v8.6.0
// PHP 8.4 新增回调四件套;8.5 新增 array_first/array_last。
// 回调接收($value, $key),全部命中即停(短路)。
$scores = ['alice' => 92, 'bob' => 47, 'carol' => 88];
var_dump(array_all($scores, fn($v) => $v > 40));      // 全部通过
var_dump(array_any($scores, fn($v) => $v < 50));      // 至少一个通过
var_dump(array_find($scores, fn($v) => $v > 80));     // 首个匹配的值
var_dump(array_find_key($scores, fn($v) => $v > 80)); // 首个匹配的键
var_dump(array_first($scores));                       // 首值
var_dump(array_last($scores));                        // 尾值
输出
bool(true)
bool(true)
int(92)
string(5) "alice"
int(92)
int(88)

Python v3.15.2

v3.15.2
# Python:all()/any() 是内置函数;find 用 next() 惯用法
scores = {"alice": 92, "bob": 47, "carol": 88}
print(all(v > 40 for v in scores.values()))
print(any(v < 50 for v in scores.values()))
print(next(v for v in scores.values() if v > 80))   # 首个匹配的值
print(next(k for k, v in scores.items() if v > 80)) # 首个匹配的键
vals = list(scores.values())
print(vals[0])  # 首值
print(vals[-1]) # 尾值
输出
True
True
92
alice
92
88

Rust v1.99.1

v1.99.1
fn main() {
    let scores = [("alice", 92), ("bob", 47), ("carol", 88)];
    println!("{}", scores.iter().all(|&(_, v)| v > 40));
    println!("{}", scores.iter().any(|&(_, v)| v < 50));
    println!("{}", scores.iter().find(|&&(_, v)| v > 80).map(|&(_, v)| v).unwrap());
    println!("{}", scores.iter().find(|&&(_, v)| v > 80).map(|&(k, _)| k).unwrap());
    println!("{}", scores.first().map(|&(_, v)| v).unwrap()); // array_first
    println!("{}", scores.last().map(|&(_, v)| v).unwrap());  // array_last
}
输出
true
true
92
alice
92
88

TypeScript v26.13.1

v26.13.1
// 运行时同 JS;Record 类型让字典形状显式化
const scores: Record<string, number> = { alice: 92, bob: 47, carol: 88 };
const vals: number[] = Object.values(scores);
console.log(vals.every((v: number) => v > 40));
console.log(vals.some((v: number) => v < 50));
console.log(vals.find((v: number) => v > 80));
console.log(vals.findIndex((v: number) => v > 80));
console.log(vals.at(0));
console.log(vals.at(-1));
输出
true
true
92
0
92
88

语言差异说明

C:无内置容器与高阶谓词,示例用函数指针手写 all/any/find(回调收值与下标,对应 PHP 的 value+key);find 返回下标充当 array_find_key 的对应物。

C++:模板 + lambda 手写同款循环;std::vector 的 front/back 即 array_first/last。

C#:LINQ 即原生对应:All/Any/First(predicate) 与 PHP 族一一对应,First()/Last() 对应 array_first/last;示例用 KeyValuePair 数组保证遍历顺序确定。

Go:标准库无泛型查找,手写循环;注意 all/any 结果与遍历顺序无关(map 乱序也安全),而「首个匹配」必须按固定键序遍历——示例用 keys 切片保序。

Java:Stream.allMatch/anyMatch/filter(...).findFirst() 对应前四件;流没有 first/last,示例物化 List 后取下标。

JavaScript:原生最全:every/some/find/findIndex 对应回调四件套,at(0)/at(-1) 对应 array_first/last——与 PHP 8.4/8.5 的补齐方向完全一致。

PHP:8.4 新增 array_all/array_any/array_find/array_find_key(回调签名为 callback(mixed $value, mixed $key): bool,两个参数都会传入——内部函数如 is_integer 会因此抛 ArgumentCountError),8.5 新增 array_first/array_last;短路语义:命中即停。array_find 找不到返回 null,若 null 本身可能是合法值,手册建议改用 array_find_key(null 不可能是键,无歧义)。

Python:all()/any() 内置,收生成器表达式;没有 find 函数——惯用法是 next((x for x in ... if ...), default),找不到抛 StopIteration(示例数据必命中)。

Rust:Iterator::all/any/find 原生对应,且是惰性短路;数组字面量配 first()/last() 对应 8.5 双件。

TypeScript:运行时同 JS;Record<string, number> 类型注解让字典形状显式化。