array_search
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
在数组中查找值并返回对应的键,未找到返回 false。
C C23
#include <stdio.h>
int main(void) {
int xs[] = {1, 2, 3};
int found = -1;
for (int i = 0; i < 3; i++) {
if (xs[i] == 2) {
found = i;
break;
}
}
printf("%d\n", found);
return 0;
}
1
C++ C++26
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> xs{1, 2, 3};
auto it = std::find(xs.begin(), xs.end(), 2);
std::cout << (it == xs.end() ? -1 : it - xs.begin()) << "\n";
return 0;
}
1
C# v11.0.100
var xs = new[] { 1, 2, 3 };
Console.WriteLine(Array.IndexOf(xs, 2));
Console.WriteLine(Array.IndexOf(xs, 9));
1 -1
Go v1.27.4
package main
import (
"fmt"
"slices"
)
func main() {
xs := []int{1, 2, 3}
fmt.Println(slices.Index(xs, 2), slices.Index(xs, 9))
}
1 -1
Java v27.0.1
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> xs = List.of(1, 2, 3);
System.out.println(xs.indexOf(2));
System.out.println(xs.indexOf(9));
}
}
1 -1
JavaScript v26.13.1
const xs = [1, 2, 3];
console.log(xs.indexOf(2), xs.indexOf(9), xs.findIndex((v) => v > 2));
1 -1 2
PHP v8.6.0
$xs = ["a" => 1, "b" => "2", "c" => 3];
echo json_encode([array_search(2, $xs), array_search("2", $xs, true), array_search(9, $xs)]);
["b","b",false]
Python v3.15.2
xs = [1, 2, 3]
print(xs.index(2))
print(xs.index(3) if 3 in xs else "missing")
1 2
Rust v1.99.1
fn main() {
let xs = [1, 2, 3];
println!("{:?}", xs.iter().position(|&v| v == 2));
println!("{:?}", xs.iter().position(|&v| v == 9));
}
Some(1) None
TypeScript v26.13.1
const xs: number[] = [1, 2, 3];
console.log(xs.indexOf(2), xs.indexOf(9), xs.findIndex((v) => v > 2));
1 -1 2
语言差异说明
C:手写线性查找(示例);标准库 bsearch 只做二分且需预排序。
C++:std::find 返回迭代器,越界判断 == end() 后可做指针差(示例);std::find_if 对应带谓词查找。
C#:Array.IndexOf/List<T>.IndexOf,未找到返回 -1(示例);谓词版用 FindIndex。
Go:1.21+ 的 slices.Index 直接可用(示例);此前需手写循环;未找到返回 -1。
Java:List.indexOf 返回索引或 -1(示例);数组用 Arrays/循环;谓词版可用 stream filter + findFirst。
JavaScript:indexOf 用严格相等(===),对象等引用类型比身份;谓词版是 findIndex(示例第 3 项);未找到均返回 -1。
PHP:返回的是键而非位置(示例返回 "b");默认松散比较——array_search(2, ...) 会命中字符串 "2"(示例第一项),字符串 haystack 强烈建议 $strict = true;未找到返回 false,注意用 !== false 判别(索引 0 会误判 falsy)。
Python:list.index 未找到抛 ValueError(其余语言的 -1/false/None 风格完全不同)——惯用先 in 预判(示例第二行);返回首个匹配下标。
Rust:iter().position(...) 返回 Option<usize>——Some(索引)/None 用类型系统消灭「忘判未找到」这一类 bug(示例)。
TypeScript:同 JavaScript 的 indexOf/findIndex(示例)。