is_array
is_array(mixed $value): bool
检测变量是否为数组。
C C23
C23
#include <stdio.h>
int main(void) {
int a[3] = {1, 2, 3};
int *p = a;
printf("%zu %zu\n", sizeof a, sizeof p);
return 0;
}
输出
12 8
C++ C++26
C++26
#include <iostream>
#include <type_traits>
int main() {
int a[3] = {1, 2, 3};
int *p = a;
std::cout << std::boolalpha
<< std::is_array_v<decltype(a)> << " "
<< std::is_array_v<decltype(p)> << "\n";
return 0;
}
输出
true false
C# v11.0.100
v11.0.100
object[] xs = { new[] { 1, 2 }, "x" };
Console.WriteLine(xs[0] is Array);
Console.WriteLine(xs[1] is Array);
输出
True False
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"reflect"
)
func main() {
values := []any{[]int{1, 2}, "x"}
for _, v := range values {
fmt.Println(reflect.TypeOf(v).Kind() == reflect.Slice)
}
}
输出
true false
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
Object[] xs = { new int[]{1, 2}, "x" };
Object first = xs[0];
Object second = xs[1];
System.out.println(first instanceof int[]);
System.out.println(second instanceof int[]);
}
}
输出
true false
JavaScript v26.13.1
v26.13.1
console.log([Array.isArray([1, 2]), Array.isArray("x")]);
输出
[ true, false ]
PHP v8.6.0
v8.6.0
echo json_encode([is_array([1, 2]), is_array("x")]);
输出
[true,false]
Python v3.15.2
v3.15.2
print([isinstance(x, list) for x in [[1, 2], "x"]])
输出
[True, False]
Rust v1.99.1
v1.99.1
use std::any::Any;
fn main() {
let xs: Vec<Box<dyn Any>> = vec![Box::new([1i32, 2]), Box::new("x".to_string())];
for x in &xs {
println!("{}", x.is::<[i32; 2]>());
}
}
输出
true false
TypeScript v26.13.1
v26.13.1
console.log([Array.isArray([1, 2]), Array.isArray("x")]);
输出
[ true, false ]
语言差异说明
C:没有运行时数组类型:数组传参退化为指针,唯一可见差异是 sizeof——数组名给整个数组大小,指针只给指针本身大小(本例 12 字节 vs 8 字节,64 位平台)。
C++:静态语言编译期已知类型,用 std::is_array_v。
C#:在 object 上用 is Array(编译期已知类型)。
Go:用 reflect 检查 Kind 是否为 Slice。
Java:在 object 上用 instanceof(编译期已知类型)。
JavaScript:必须用 Array.isArray(typeof 对数组返回 "object",不能区分)。
PHP:is_array 检测关联/列表数组。
Python:对应用 isinstance(x, list)。
Rust:对 Box<dyn Any> 用 Any::is::<[T; N]>。
TypeScript:同 JS,必须用 Array.isArray。