php 中数组或 null 比较的最佳方法
Best way for array or null comparison in php
我有 $result 变量,它可以是数组或 null。
如果它不是空数组,我会说它是真的
如果它为空,我会说它是假的。
我在想几个方法比如
#1
$array = array (
$res => is_null($result)
);
#2
$array = array (
$res => $result !== null? true : false,
);
但我对这两种方式都不那么自信。你有更好的推荐吗?
我认为您正在寻找 empty 函数。来自文档:
The following values are considered to be empty:
- ""(空字符串)
- 0(整数 0)
- 0.0(0 作为浮点数)
- "0"(0 作为字符串)
- 空
- 错误
- array()(空数组)
你没有说你的变量可以潜在地保存这些其他值,所以我假设它不能。这意味着您可以简单地检查 !empty($result)
.
例如:
function v($r){
return !empty($r);
}
assert(false === v(null));
assert(false === v([]));
assert(true === v([1]));
我有 $result 变量,它可以是数组或 null。 如果它不是空数组,我会说它是真的 如果它为空,我会说它是假的。
我在想几个方法比如
#1
$array = array (
$res => is_null($result)
);
#2
$array = array (
$res => $result !== null? true : false,
);
但我对这两种方式都不那么自信。你有更好的推荐吗?
我认为您正在寻找 empty 函数。来自文档:
The following values are considered to be empty:
- ""(空字符串)
- 0(整数 0)
- 0.0(0 作为浮点数)
- "0"(0 作为字符串)
- 空
- 错误
- array()(空数组)
你没有说你的变量可以潜在地保存这些其他值,所以我假设它不能。这意味着您可以简单地检查 !empty($result)
.
例如:
function v($r){
return !empty($r);
}
assert(false === v(null));
assert(false === v([]));
assert(true === v([1]));