PHP中能否将implode()作为判断条件?如何检测数组是否可被implode?
PHP数组安全implode的实现方案
现有写法的问题
你编写的if (implode($array))判断逻辑完全不可行,原因有两点:
- 只要数组顶层元素中存在数组、资源、未实现
__toString()方法的对象,调用implode时会直接抛出Array to string conversion类的警告,不会返回false,判断逻辑本身就会触发错误 - 即使数组可正常implode,若拼接结果为空字符串(比如数组元素全为空、数组本身为空),也会被判断为false,出现误判
你之前提到的count($array) == count($array, COUNT_RECURSIVE)判断方案也无法满足需求,因为空子数组的递归计数和非递归计数差值为0,无法识别出顶层存在空数组的场景。
可implode数组的最优检测方案
implode只会处理数组的顶层元素,只要所有顶层元素均为标量类型(字符串、整型、浮点型、布尔型)或NULL,就可以安全调用implode,对应的检测函数实现如下:
function isImplodable(array $array): bool { foreach ($array as $item) { if (!is_scalar($item) && $item !== null) { return false; } } return true; }
使用示例:
$array1 = ["cat", "dog"]; var_dump(isImplodable($array1)); // 输出 bool(true),可安全执行implode $array2 = [ "cat", "dog", 1 => ["wolf", "lion"] ]; var_dump(isImplodable($array2)); // 输出 bool(false),顶层存在非空数组,不可执行implode $array3 = [ "cat", "dog", 1 => [] ]; var_dump(isImplodable($array3)); // 输出 bool(false),顶层存在空数组,不可执行implode
检测通过后即可安全调用implode:
if (isImplodable($array)) { $builded = implode(',', $array); }
兼容多维数组的拼接方案
如果你的需求是无论数组多少维都要完成拼接,可以先将数组扁平化提取所有标量元素,再执行implode:
function flattenImplode(string $separator, array $array): string { $result = []; array_walk_recursive($array, function($item) use (&$result) { if (is_scalar($item) || $item === null) { $result[] = $item; } }); return implode($separator, $result); } // 测试多维数组 echo flattenImplode(',', $array2); // 输出 cat,dog,wolf,lion echo flattenImplode(',', $array3); // 输出 cat,dog
内容的提问来源于stack exchange,提问作者Camille
相关产品推荐
相关产品推荐

