gpt4 book ai didi

php - 为什么将 false 转换为数组不会导致空数组

转载 作者:行者123 更新时间:2023-12-04 22:31:49 24 4
gpt4 key购买 nike

我有一个方法返回类型可以是一个数组或 false。

因此,我将结果转换为一个数组,以确保我的代码不需要检查 false 或数组。

但是,php 将 false 转换为包含 1 个元素的数组:false:

array(1) {
[0]=>
bool(false)
}

为什么!

没有 if 语句有没有办法实现这个?

if ($returnValue === false) {
return array();
} else {
return $returnValue;
}

最佳答案

按设计工作。 The manual specifies :

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

你不能简单地使用 ternary operator

return (is_array($returnValue) ? $returnValue : array());

关于php - 为什么将 false 转换为数组不会导致空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com