trim()函数:如果参数是unset/null变量,如何避免返回空字符串?

eas*_*der 5 php trim array-map

我在php中使用trim()函数时遇到问题.

//Suppose the input variable is null.
$input = NULL;
echo (trim($input));
Run Code Online (Sandbox Code Playgroud)

如上所示,如果输入参数为NULL,则代码的输出为空字符串.有什么方法可以避免这种情况吗?如果输入未设置或为NULL值,则默认情况下修剪将返回空字符串.

这让我很难使用如下的装饰.

array_map('trim', $array);
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何方法可以完成相同的结果而不是循环遍历数组.我还注意到trim函数有第二个参数,通过传递第二个参数,你可以避免一些charlist.但它似乎对我不起作用.

有任何想法吗?谢谢.

Jon*_*nah 8

创建一个代理函数,以确保它在运行之前是一个字符串trim().

function trimIfString($value) {
    return is_string($value) ? trim($value) : $value;
}
Run Code Online (Sandbox Code Playgroud)

然后当然把传给了array_map().

array_map('trimIfString', $array);
Run Code Online (Sandbox Code Playgroud)