empty
empty(mixed $var): bool
检查变量是否为空(语言构造:""、0、"0"、null、false、[] 或未定义均视为空)。
C C23
#include <stdio.h>
int main(void) {
const char *s = "";
int n = 0;
printf("%d %d\n", s[0] == '\0', n == 0);
return 0;
}
1 1
C++ C++26
#include <iostream>
#include <string>
int main() {
std::string s = "";
int n = 0;
std::cout << std::boolalpha << s.empty() << " " << (n == 0) << "\n";
return 0;
}
true true
C# v11.0.100
string s = "";
int n = 0;
Console.WriteLine(string.IsNullOrEmpty(s));
Console.WriteLine(n == 0);
True True
Go v1.27.4
package main
import "fmt"
func main() {
s := ""
n := 0
fmt.Println(s == "", n == 0)
}
true true
Java v27.0.1
public class Main {
public static void main(String[] args) {
String s = "";
int n = 0;
System.out.println(s.isEmpty());
System.out.println(n == 0);
}
}
true true
JavaScript v26.13.1
console.log([!"", !0, Boolean("0"), Boolean(null), !1, Boolean("a")]);
[ true, true, true, false, false, true ]
PHP v8.6.0
// empty 是语言构造:对 "0" 也返回 true,且对未定义变量不告警
echo json_encode([empty(""), empty(0), empty("0"), empty(null), empty(1), empty("a")]);
[true,true,true,true,false,false]
Python v3.15.2
print([not "", not 0, bool("0"), bool(None), not 1, bool("a")])
[True, True, True, False, False, True]
Rust v1.99.1
fn main() {
let s = "";
let n = 0;
println!("{} {}", s.is_empty(), n == 0);
}
true true
TypeScript v26.13.1
console.log([!"", !0, Boolean("0"), Boolean(null), !1, Boolean("a")]);
[ true, true, true, false, false, true ]
语言差异说明
C:没有布尔隐式转换的通用约定,空值检查按类型分别写——字符串看首字符 \0、数值比 == 0、指针比 == NULL(示例覆盖前两类)。
C++:容器/字符串有 empty(),数值显式比 == 0(示例);指针可用隐式 if (!ptr)。
C#:没有语言级「空即真」判断;字符串用 string.IsNullOrEmpty(示例),数值显式比较;注意 PHP 的 empty("0") 为 true 而 C# 的 "0" 非空。
Go:没有 truthiness,一律显式比较(示例:s == ""、n == 0);Go 的哲学是让「空」的定义在每个调用点显式可见。
Java:同 Go,无 truthiness;字符串 isEmpty()、数值 == 0(示例);注意 "0" 在 Java 中非空。
JavaScript:falsy 语义最接近 empty——""、0、null、undefined、NaN、false 均为假;但 "0" 是 truthy(示例第 3 项 Boolean("0") 为 true),这是与 PHP empty 最大的语义分歧。
PHP:empty 是语言构造,判定集比 JS 更宽——""、0、"0"、null、false、[]、未定义变量全部为空(示例中 empty("0") 为 true);对未定义变量返回 true 且不告警,等价于 !isset($x) || (bool)$x == false。
Python:falsy 集合与 JS 基本一致(""、0、None、[]、False);"0" 同样是 truthy(示例第 3 项),不含 JS 的 NaN/undefined 概念。
Rust:没有隐式 truthiness,一切按类型显式判断——字符串 is_empty()、数值 == 0、Option 用 is_none()(示例覆盖前两类)。
TypeScript:同 JavaScript;借助类型系统还能把「可能为空」表达为 string | undefined 并用 strictNullChecks 强制处理。