php空值替换功能 [英] php null replacement function
问题描述
Visual Basic 中有一个名为 Nz() 的函数用于应用程序.该函数检查变量是否为空,如果发现变量为空,则返回一个提供的值.
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.
我尝试在 php 中编写相同的函数,如下所示:
i try to write the same function in php, which looks like below:
function replace_null($value, $replace) {
if (!isset($value)) {
return $replace;
} else {
return $value;
}
}
$address = replace_null($data['address'], 'Address is not available.');
当然,如果发现$data['address']
为null,php将停止执行代码并且不会调用replace_null
.
of course, if $data['address']
is found null, php will stop executing the code and replace_null
won't be called.
我目前正在使用三元
(isset(data['address']) ? data['address'] : 'Address is not available.');
但我认为replace_null
,如果它有效,会提供一种更方便的方法.
but i think replace_null
, if it works, will offer a more convenient way.
php 中是否有提供与 vba 的 Nz() 相同功能的函数?任何建议将不胜感激.
is there a function in php that provide the same functionality as vba's Nz()? any suggestion will be appreciated.
提前致谢.
推荐答案
有点迂回:如果你只用这个来检查数组成员,你可以单独传递密钥:
A bit roundabout: If you only use this to check for array members, you could pass the key separately:
function get_with_default($arr, $key, $defval)
{
return isset($arr[$key]) ? $arr[$key] : $defval;
}
如果变量可以设置但为空(它不能,感谢@deceze),添加另一个检查:
If the variable could be set but null ( which it cannot, thanks @deceze), add another check:
function get_and_coalesce_with_default($arr, $key, $defval)
{
return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
正如所指出的,isset()
只在非空值上成功,所以上面没有添加任何东西.不过,我们可以使用 array_key_exists
编写一个非平凡的检查:
As pointed out, isset()
only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists
, though:
function get_with_default_v2($arr, $key, $defval)
{
return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
这篇关于php空值替换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!